package main
import "fmt"
func main() {
dataChan := make(chan int, 5)
syncChan1 := make(chan struct{}, 1)
syncChan2 := make(chan struct{}, 2) //主协程信号量,如果没有这个通道,会瞬间停止
go func() { //用于演示接收操作
<-syncChan1
for {
if elem, ok := <-dataChan; ok {
fmt.Printf("Received: %d [receiver]\n", elem)
} else {
break
}
}
fmt.Println("Done. [receiver]")
syncChan2 <- struct{}{}
}()
go func() { //用于演示发送操作
for i := 0; i < 5; i++ {
dataChan <- i
fmt.Printf("Sent: %d [sender]\n", i)
}
close(dataChan) //关闭通道
syncChan1 <- struct{}{}//两个通道间发送信号量
fmt.Println("Done. [sender]")
syncChan2 <- struct{}{}
}()
<-syncChan2 //分别为接收和发送的信号,不能注释掉
<-syncChan2
}
/*
输出结果:
Sent: 0 [sender]
Sent: 1 [sender]
Sent: 2 [sender]
Sent: 3 [sender]
Sent: 4 [sender]
Done. [sender]
Received: 0 [receiver]
Received: 1 [receiver]
Received: 2 [receiver]
Received: 3 [receiver]
Received: 4 [receiver]
Done. [receiver]
*/
管道通信与关闭
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- socket网络跨主机的进程间通信是以五元组【源IP,源端口,目的IP,目的端口,TCP或UDP协议】,来找到不同...
- 胶片摄影在最近几十年中一直都处于一个艰难的时期。像是 Agfa、Kodak、Fujifilm 都不得不面对逐渐萎缩...