Skip to content

Instantly share code, notes, and snippets.

@barryz
Last active February 12, 2018 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barryz/cc6bcf32ced1544c3dcef83e012129eb to your computer and use it in GitHub Desktop.
Save barryz/cc6bcf32ced1544c3dcef83e012129eb to your computer and use it in GitHub Desktop.
Go: example of channel broadcast
package main
import (
"fmt"
"time"
)
func main() {
done := make(chan struct{})
go func() {
time.Sleep(3 * time.Second)
fmt.Println("producer task done!")
close(done) // 所有阻塞的goroutine都能收到done信号, 可以当做cond.Broadcast使用
// done <- struct{}{} // 只有一个goroutine能收到done信号
}()
for i := 0; i < 4; i++ {
go func(i int) {
fmt.Printf("[%d] waiting for task done..\n", i)
<-done
fmt.Printf("[%d] task already done\n", i)
return
}(i)
}
<-done
time.Sleep(time.Second)
fmt.Println("main goroutine exit...")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment