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

通道(Chanels)--协程交互(匿名函数)

作者: bocsoft | 来源:发表于2018-12-03 16:50 被阅读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 func() { // 用于演示接收操作
            <-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{}{}
        }()
    
        go func() { //用于演示发送操作
            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 seconds...[sender]")
            time.Sleep(time.Second * 2)
            close(strChan)
            syncChan2 <- struct{}{}
        }()
    
        //如果下面两个语句都注释掉的化,程序会瞬间执行结束
        <-syncChan2
        <-syncChan2
    }
    
    
    // 输出 结果:
    /*
    
    Sent: a [sender]
    Sent: b [sender]
    Sent: c [sender]
    Sent a sync signal. [sender]
    Received a sync signal and wait a second...[receiver]
    Received: a [receiver]
    Received: b [receiver]
    Sent: d [sender]
    Wait 2 seconds...[sender]
    Received: c [receiver]
    Received: d [receiver]
    Stopped. [receiver]
    
    Process finished with exit code 0
    
     */
    
    
    
    
    

    相关文章

      网友评论

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

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