Last active
February 12, 2018 10:08
-
-
Save barryz/cc6bcf32ced1544c3dcef83e012129eb to your computer and use it in GitHub Desktop.
Go: example of channel broadcast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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