sync.WaitGroup控制无效?

yaxiaomu · · 1031 次点击
## 这样吧。。 ``` func main() { ch2 := make(chan int, 1000) var wg sync.WaitGroup wg.Add(3) go testThreadSate01(ch2, &wg) go testThreadSate02(ch2, &wg) go testThreadSate03(ch2, &wg) wg.Wait() for { select { case resGt := <-ch2: if resGt > 28 { fmt.Println("有bug !") goto OUT } default: } } OUT: fmt.Println("----") fmt.Println("main done") } ```
#3
更多评论
实际上你的协程可能来不及执行wg.Add(1)主程就退出了,而且你的go func() {}是个死循环只不过你的主程没有去等待这个协程才没有卡住
#1
嗯,理解,有什么补救办法吗,我改了另外一种方式, ``` package main import ( "fmt" "sync" ) func main() { ch2 := make(chan int, 1000) var wg sync.WaitGroup wg.Add(4) go testThreadSate01(ch2, &wg) go testThreadSate02(ch2, &wg) go testThreadSate03(ch2, &wg) go func(wg *sync.WaitGroup) { for { select { case res := <-ch2: if res == 28 { break } case resGt := <-ch2: if resGt > 28 { fmt.Println("有bug !") wg.Done() } default: } } }(&wg) wg.Wait() fmt.Println("main done") } func testThreadSate03(ch chan int, wg *sync.WaitGroup) { defer wg.Done() for j := 21; j <= 30; j++ { ch <- j } } func testThreadSate01(ch chan int, wg *sync.WaitGroup) { defer wg.Done() for j := 0; j <= 10; j++ { ch <- j } } func testThreadSate02(ch chan int, wg *sync.WaitGroup) { defer wg.Done() //time.Sleep(1 * time.Microsecond) for j := 11; j <= 20; j++ { ch <- j } } ```
#2