download1214 2017-06-30 10:47
浏览 58
已采纳

如何有效关闭渠道?

I'm trying to do some stuff:

type Feed struct {
    title, descr, link string
    published          time.Time
}
func main() {
    ar := make([]Feed, 0)
    for i := 0; i < 3; i++ {
        f: = new(Feed)
        // do some stuff with feed
        ar = append(ar, *f)
    }

    ch := make(chan Feed, 3)

    for _, i := range ar {
        go process(i, ch)
    }

    r :=0
    for i := range ch {
        fmt.Println(i)
        r++
        if r == 3 {
            close(ch)
        }
    }
}
func process(i Feed, ch chan Feed) {
 // do some stuff
 ch <- i
}

It seems that ar is unnecessary, but if it would be removed, last range would be forever. What i'm doing wrong?

Another question is - is that way of working with Go routines the right way?

  • 写回答

1条回答 默认 最新

  • douyu9012 2017-06-30 13:22
    关注

    Here is an example producer-consumer type. I only use the WaitGroup here so that the main goroutine wouldn't exit instantly. Theoretically your application could either wait, or do some other interesting stuff in the mean time.

    Note that you could also use a buffered channel using c := make(chan(*Feed, n)) where n is the number you want buffered. Just be aware that in a typical producer-consumer scenario, there is sometimes a lot of resources allocated per job. So depending on that you could buffer just a few, or all of them if you wanted.

    Without a buffered channel, it acts as a sync between the goroutines. Producers block at c <- waiting for a consumer's <- c to hand off to, so only one of each routine execute these lines at a time.

    EDIT I added a pause before printing "started" to make the output less synchronized. It previously always output:

    created
    started
    created
    started
    ...
    

    https://play.golang.org/p/FmWqegr-CR

    package main
    
    import (
        "fmt"
        "math/rand"
        "sync"
        "time"
    )
    
    type Feed struct {
        title, descr, link string
        published          time.Time
    }
    
    func CreateFeed() *Feed {
        r := rand.Int() % 500
        time.Sleep(1000 + time.Duration(r)*time.Millisecond)
        fmt.Println("Feed created")
        return &Feed{
            published: time.Now(),
        }
    }
    
    func UseFeed(f *Feed) {
        time.Sleep(100 * time.Millisecond)
        fmt.Println("Feed started")
        time.Sleep(1600 * time.Millisecond)
        fmt.Printf("Feed consumed: %s
    ", f.published)
    }
    
    func main() {
        numFeeds := 10
    
        var wg sync.WaitGroup
        wg.Add(10)
    
        c := make(chan (*Feed))
        for i := 0; i < numFeeds; i++ {
            go func() { c <- CreateFeed() }()
        }
    
        for i := 0; i < numFeeds; i++ {
            go func() {
                f := <-c
                UseFeed(f)
                wg.Done()
            }()
        }
    
        wg.Wait()
    }
    

    I'm hoping this is what you are looking for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器