go 实现生产者与消费者模型,如何判断channel中数据已全部消费?

package main


import (

    "fmt"

)


var c = make(chan int, 50)

var count = 0


func main() {

    for i := 0; i < 5; i++ {

        go consumer(i)

    }

    for i := 0; i < 1000; i++ {

        c <- i

    }

    /** here **/

    fmt.Println(count)

}


func consumer(index int) {

    for target := range c {

        fmt.Printf("no.%d:%d\n", index, target)

        count++

    }

}


请问代码中注释处,如何才能确保c中的数据已经全部被消费?(默认time.Sleep()无法保证,不能使用)
如果不能确保的话,那么主线程会提前退出,部分数据就会被抛弃了。

守着星空守着你
浏览 1954回答 2
2回答

呼啦一阵风

这种可以使用sync里的WaitGroup工具来做等待,也可以单独开个channel来等待。如果只是想单纯的保证goroutine全部执行完毕再退出main,可以定义个相同数量buffer的channel,每个goroutine执行结束后就写入这个channel,而main只要消费等待channel就可以达到阻塞的目的了。类似这样var c = make(chan int, 50)var count = 0var retChannel = make(chan int,5)func main() {&nbsp; &nbsp; for i := 0; i < 5; i++ {&nbsp; &nbsp; &nbsp; &nbsp; go consumer(i)&nbsp; &nbsp; }&nbsp; &nbsp; for i := 0; i < 1000; i++ {&nbsp; &nbsp; &nbsp; &nbsp; c <- i&nbsp; &nbsp; }&nbsp; &nbsp; /** here **/&nbsp; &nbsp; close(c)&nbsp; &nbsp; for i := 0; i < 5; i++ {&nbsp; &nbsp; &nbsp; &nbsp; <-retChannel&nbsp; &nbsp; }&nbsp; &nbsp; close(retChannel)&nbsp; &nbsp; fmt.Println(count)}func consumer(index int) {&nbsp; &nbsp; for target := range c {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("no.%d:%d\n", index, target)&nbsp; &nbsp; &nbsp; &nbsp; count++&nbsp; &nbsp; }&nbsp; &nbsp; retChannel <- index}

慕标琳琳

package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sync")var c = make(chan int, 50)var count = 0var wg = new(sync.WaitGroup)func main() {&nbsp; &nbsp; for i := 0; i < 5; i++ {&nbsp; &nbsp; &nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; &nbsp; &nbsp; go consumer(i)&nbsp; &nbsp; }&nbsp; &nbsp; for i := 0; i < 1000; i++ {&nbsp; &nbsp; &nbsp; &nbsp; c <- i&nbsp; &nbsp; }&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; close(c)&nbsp; &nbsp; /** here **/&nbsp; &nbsp; fmt.Println(count)}func consumer(index int) {&nbsp; &nbsp; for target := range c {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("no.%d:%d\n", index, target)&nbsp; &nbsp; &nbsp; &nbsp; count++&nbsp; &nbsp; &nbsp; &nbsp; if len(c) <= 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go