1

channel实现一生产,多消费,如何死锁呢(在不closechan的情况下)

 2 years ago
source link: https://studygolang.com/articles/35355
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

channel实现一生产,多消费,如何死锁呢(在不closechan的情况下)

yaxiaomu · 12天之前 · 359 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    
package main

import (
    "fmt"
    "sync"
)

func main() {
    wg:=&sync.WaitGroup{}
    ch:=make(chan int ,100)
    send:= func() {
        for i:=0;i<100;i++{
            ch<-i
        }
        //不开启close,如何不死锁?
        //close(ch)
    }
    recv:= func(id int) {
        defer wg.Done()
        for i:=range ch{
            fmt.Printf("cusumerV1 #%d get %d\n", id, i)
        }
        fmt.Printf(" >>>>>>consumerV1 #%d exit,\n", id)

        for{
             if i,ok := <-ch;ok{
                fmt.Printf("cusumerV2 #%d get %d,closed is %v\n", id, i,ok)
            }else{
                 fmt.Printf(" >>>>>>consumerV2 #%d exit,closed is %v\n", id,ok)
                return
             }

        }
    }

    wg.Add(3)
    go recv(0)
    go recv(1)
    go recv(2)
    go send()
    wg.Wait()
    fmt.Println("all done")
}

对close的行为很迷惑,只是一个标记位,为啥不close会死锁呢。。


有疑问加站长微信联系(非本文作者))

280

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:701969077


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK