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