Created
September 20, 2013 16:28
-
-
Save cuixin/6640196 to your computer and use it in GitHub Desktop.
close two channels example in golang.
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 WaitMany(a, b chan bool) { | |
| for a != nil || b != nil { | |
| select { | |
| case _, ok := <-a: | |
| if !ok { | |
| fmt.Println("a closed") | |
| a = nil | |
| } | |
| case _, ok := <-b: | |
| if !ok { | |
| fmt.Println("b closed") | |
| b = nil | |
| } | |
| } | |
| } | |
| } | |
| func main() { | |
| a, b := make(chan bool), make(chan bool) | |
| t0 := time.Now() | |
| go func() { | |
| fmt.Println("Start") | |
| time.Sleep(1 * time.Second) | |
| close(a) | |
| time.Sleep(2 * time.Second) | |
| close(b) | |
| }() | |
| WaitMany(a, b) | |
| fmt.Println("Wait %v for waitmany", time.Since(t0)) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
为什么采用把Channel置成nil,因为nil的channel是deadlock的,例如
var ch chan bool
ch <- true
这是完全堵塞的,如果不这么做,先关闭了A,然后下次还可能继续读到A,这个代码可以简化不需要判断ok的~