Skip to content

Instantly share code, notes, and snippets.

@cuixin
Created September 20, 2013 16:28
Show Gist options
  • Select an option

  • Save cuixin/6640196 to your computer and use it in GitHub Desktop.

Select an option

Save cuixin/6640196 to your computer and use it in GitHub Desktop.
close two channels example in golang.
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))
}
@cuixin

cuixin commented Apr 25, 2014

Copy link
Copy Markdown
Author

为什么采用把Channel置成nil,因为nil的channel是deadlock的,例如
var ch chan bool
ch <- true
这是完全堵塞的,如果不这么做,先关闭了A,然后下次还可能继续读到A,这个代码可以简化不需要判断ok的~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment