done := make(chanstruct{}) gofunc() { doLongRunningThing() close(done) }() // do some other things // wait for that long running thing to finish <-done
2. 多任务同时开始
实现类似并行而非并发的效果
1 2 3 4 5 6 7 8 9 10
start := make(chanstruct{}) for i := 0; i < 10000; i++ { gofunc() { <-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)
3. 事件中断
1 2 3 4 5 6 7 8
for { select { case m := <-email: sendEmail(m) case <-stop: // triggered when the stop channel is closed break// (or return) exit } }