//read channel until it closes or error-conditionfor {if input, open :=<-ch; !open {break } fmt.Printf("%s", input)}
或者使用(1)自动检测。
(3)如何通过一个通道让主程序等待直到协程完成:
(信号量模式):
ch :=make(chanint) // Allocate a channel.// Start something in a goroutine; when it completes, signal on the channel.gofunc() {// doSomething ch <-1// Send a signal; value does not matter.}()doSomethingElseForAWhile()<-ch // Wait for goroutine to finish; discard sent value.
如果希望程序一直阻塞,在匿名函数中省略 ch <- 1即可。
(4)通道的工厂模板:以下函数是一个通道工厂,启动一个匿名函数作为协程以生产通道:
funcpump() chanint { ch :=make(chanint)gofunc() {for i :=0; ; i++ { ch <- i } }()return ch}
timeout :=make(chanbool, 1)gofunc() { time.Sleep(1e9) // one second timeout <-true}()select {case<-ch:// a read from ch has occurredcase<-timeout:// the read from ch has timed out}
(10)如何使用输入通道和输出通道代替锁:
funcWorker(in, out chan*Task) {for { t :=<-inprocess(t) out <- t }}