美文网首页
通道(Chanels)--协程交互(函数调用)

通道(Chanels)--协程交互(函数调用)

作者: bocsoft | 来源:发表于2018-12-03 17:36 被阅读0次
package main

import (
    "fmt"
    "time"
)

var strChan = make(chan string, 3)

func main() {
    syncChan1 := make(chan struct{}, 1)
    syncChan2 := make(chan struct{}, 2)
    go receive(strChan, syncChan1, syncChan2) //用于演示接收操作
    go send(strChan, syncChan1, syncChan2)    //用于演示发送操作

    <-syncChan2
    <-syncChan2
}

//注意通道参数的写法的理解:syncChan1 <-chan ===> syncChan1 可理解为 在函数体中 替代 <-chan,用于从通道中接收数据。
//因此函数体中的写法为:<-syncChan1  (syncChan1  在此处代表着参数中的通道,用于发出数据,在函数体中接收)
func receive(strChan <-chan string,
    syncChan1 <-chan struct{},
    syncChan2 chan<- struct{}) {
    <-syncChan1
    fmt.Println("Received a sync signal and wait a second... [receiver]")
    time.Sleep(time.Second)
    for {
        if elem, ok := <-strChan; ok {
            fmt.Println("Received:", elem, "[receiver]")
        } else {
            break
        }
    }
    fmt.Println("Stopped. [receiver]")
    syncChan2 <- struct{}{}
}

func send(strChan chan<- string,
    syncChan1 chan<- struct{},
    syncChan2 chan<- struct{}) {
    for _, elem := range []string{"a", "b", "c", "d"} {
        strChan <- elem
        fmt.Println("Sent:", elem, "[sender]")
        if elem == "c" {
            syncChan1 <- struct{}{}
            fmt.Println("sent a sync signal.[sender]")
        }
    }
    fmt.Println("Wait 2 second... [sender]")
    time.Sleep(time.Second * 2)
    close(strChan)
    syncChan2 <- struct{}{}
}

/*
输出结果:
Sent: a [sender]
Sent: b [sender]
Sent: c [sender]
sent a sync signal.[sender]
Received a sync signal and wait a second... [receiver]
Sent: d [sender]
Wait 2 second... [sender]
Received: a [receiver]
Received: b [receiver]
Received: c [receiver]
Received: d [receiver]
Stopped. [receiver]
*/


相关文章

网友评论

      本文标题:通道(Chanels)--协程交互(函数调用)

      本文链接:https://www.haomeiwen.com/subject/lcqucqtx.html