chan中的值(基础类型)

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


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




上一篇下一篇

猜你喜欢

热点阅读