原文链接:https://medium.com/@matryer/golang-advent-calendar-day-two-starting-and-stopping-things-with-a-signal-channel-f5048161018
使用channel在goroutines中传递信号
在go里,使用
传递信号时,使用
这是一个
1 | var signal chan struct{} |
可以使用go的内置
1 | signal := make(chan struct{}) |
代码会被阻塞,直到某些值被发送到
1 | <-signal |
在这个例子下,我们不在意它的值,这也是为什么我们不传递任何值给它。
类似的,在一个
等待某些操作的结束
通过一个阻塞的
1 2 3 4 5 6 7 8 9 | done := make(chan struct{}) go func() { doLongRunningThing() close(done) }() // do some other bits // wait for that long running thing to finish <-done // do more things |
同一时间执行多个任务
假设有很多的
1 2 3 4 5 6 7 8 9 10 | 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) |
暂停任务
类似的,也可以使用它去暂停
1 2 3 4 5 6 7 8 9 | loop: for { select { case m := <-email: sendEmail(m) case <-stop: // triggered when the stop channel is closed break loop // exit } } |
如果
- 更多的
channel 可以做的事件,到这里查看:VIDEO: GopherCon 2014 A Channel Compendium by John Graham-Cumming.