【发布时间】:2019-07-24 16:11:14
【问题描述】:
一旦另一个 goroutine 关闭一个通道,我正在尝试结束多个 goroutine。但是,在收到关闭信号后,我将陷入无限循环。我不知道为什么。
我知道使用 context.Context 是可能的,但我正在尝试关闭频道。
去游乐场:https://play.golang.org/p/C6pcYgGLnG9
package main
import (
"fmt"
"time"
"sync"
)
func runner(id int, ch <-chan struct{}, wg *sync.WaitGroup) {
for {
select {
case <-time.Tick(time.Second):
fmt.Println("worker ", id)
case <- ch:
fmt.Println("closing worker ", id)
break
}
}
wg.Done()
}
func main() {
fmt.Println("Hello, playground")
ch := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go runner(1, ch, &wg)
wg.Add(1)
go runner(2, ch, &wg)
time.Sleep(5*time.Second)
close(ch)
wg.Wait()
}
【问题讨论】:
标签: go