管道通信与关闭

2018-12-04  本文已影响0人  bocsoft

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]
 */




上一篇下一篇

猜你喜欢

热点阅读