在昨天的例子中,有使用到close()來關閉channel.
那怎樣來判斷channel是否已經關閉呢.
我們把昨天的程式改寫一下,為了方便對照起見,有保留原本的異動部份.
// hello71
// producer_consumer 2
package main
import (
"fmt"
"time"
)
// integer producer
func numGen(start, count int, out chan<- int) {
for i := 0; i < count; i++ {
out <- start
start += count
}
close(out)
fmt.Printf("Producer: 送完 -%v\n", time.Now())
}
// integer consumer
func numEchoRange(in <-chan int, done chan<- bool) {
//for num := range in {
// time.Sleep(time.Second)
// fmt.Printf("consumer: 收到%2d-%v\n", num, time.Now())
//}
for {
input, open := <-in
if !open {
break
}
time.Sleep(time.Second)
fmt.Printf("consumer: 收到%2d-%v\n", input, time.Now())
}
done <- true
}
func main() {
numChan := make(chan int, 100)
done := make(chan bool)
go numGen(0, 10, numChan)
go numEchoRange(numChan, done)
<-done
fmt.Println("Main():所有的工作都已完成!")
}
執行結果:
./hello71
Producer: 送完 -2014-10-18 00:30:20.62187013 +0800 CST
consumer: 收到 0-2014-10-18 00:30:21.622183431 +0800 CST
consumer: 收到10-2014-10-18 00:30:22.622331389 +0800 CST
consumer: 收到20-2014-10-18 00:30:23.622454017 +0800 CST
consumer: 收到30-2014-10-18 00:30:24.622602616 +0800 CST
consumer: 收到40-2014-10-18 00:30:25.622749231 +0800 CST
consumer: 收到50-2014-10-18 00:30:26.622897952 +0800 CST
consumer: 收到60-2014-10-18 00:30:27.623024673 +0800 CST
consumer: 收到70-2014-10-18 00:30:28.623156869 +0800 CST
consumer: 收到80-2014-10-18 00:30:29.623288408 +0800 CST
consumer: 收到90-2014-10-18 00:30:30.623407953 +0800 CST
Main():所有的工作都已完成!