使用channel在goroutines中传递信号原文链接:https://medium.com/@matryer/golang-advent-calendar-day-two-starting-and-stopping-things-with-a-signal-channel-f5048161018
channelgoroutines
空的structchannel
信号channel
var signal chan struct{}
make
signal := make(chan struct{})
channel
<-signal
在这个例子中,我们不在意它的值,这也是为什么我们不传递任何值给它。
selectgoroutinechannel
等待某些操作的结束
信号channelgoroutine
done := make(chan struct{})
go func() {
doLongRunningThing()
close(done)
}()
// do some other bits
// wait for that long running thing to finish
// 阻塞,直到goroutine中关闭channel
<-done
// do more things
同一时间执行多个任务
goroutine信号channel
start := make(chan struct{})
for i := 0; i < 10000; i++ {
go func() {
<-start // wait for the start channel to be closed
doWork(i) // do something
}()
}
// at this point, all goroutines are ready to go - we just need to
// tell them to start by closing the start channel
close(start)
暂停任务
goroutinesgoroutineemail channel
loop:
for {
select {
case m := <-email:
sendEmail(m)
case <-stop: // triggered when the stop channel is closed
break loop // exit
}
}
stop channel