美文网首页
chan中的值(基础类型)

chan中的值(基础类型)

作者: bocsoft | 来源:发表于2018-12-10 10:27 被阅读0次
    
    
    package main
    
    import (
        "fmt"
        "time"
    )
    
    var mapChan = make(chan map[string]int, 1)
    
    func main() {
        syncChan := make(chan struct{}, 2)
        //用于演示接收操作
        go func() {
            for {
                if elem, ok := <-mapChan; ok {
                    elem["count"]++
                } else {
                    break
                }
            }
            fmt.Println("Stopped. [receiver]")
    
            syncChan <- struct{}{}
        }()
    
        //用于演示发送操作
        go func() {
            countMap := make(map[string]int)
            for i := 0; i < 5; i++ {
                mapChan <- countMap
                time.Sleep(time.Millisecond)
                fmt.Printf("The count map: %v. [sender]\n", countMap)
            }
    
            //发送完之后,必须关闭管道,不然会报错误:fatal error: all goroutines are asleep - deadlock!
            close(mapChan)
            syncChan <- struct{}{}
        }()
        <-syncChan
        <-syncChan
    
    }
    
    /*
     输出结果:
    The count map: map[count:1]. [sender]
    The count map: map[count:2]. [sender]
    The count map: map[count:3]. [sender]
    The count map: map[count:4]. [sender]
    The count map: map[count:5]. [sender]
    Stopped. [receiver]
     */
    
    
    
    
    

    相关文章

      网友评论

          本文标题:chan中的值(基础类型)

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