标签:
看过好几遍了,觉得挺实用的,记录备忘一下。
1.开启很多个 goroutine 之后,等待执行完毕
type WaitGroupWrapper struct { sync.WaitGroup } func (w *WaitGroupWrapper) Wrap(cb func()) { w.Add(1) go func() { cb() w.Done() }() } // can be used as follows: wg := WaitGroupWrapper{} wg.Wrap(func() { n.idPump() }) ... wg.Wait()
2.程序要关闭了,通知各个goroutine安全退出
func work() { exitChan := make(chan int) go task1(exitChan) go task2(exitChan) time.Sleep(5 * time.Second) close(exitChan) } func task1(exitChan chan int) { <-exitChan log.Printf("task1 exiting") } func task2(exitChan chan int) { <-exitChan log.Printf("task2 exiting") }
原文参考:
http://nsq.io/overview/internals.html
标签:
原文地址:http://www.cnblogs.com/zhangqingping/p/4326019.html