为什么我的golang goroutine代码陷入僵局

我试图用通道写一些goroutine,但陷入了僵局,为什么?我是不是跟WaitGroup做错了,太糊涂了...


package main


import (

    "fmt"

    "sync"

)


var wg sync.WaitGroup


func main() {

    chan1 := make(chan string)

    chan2 := make(chan string)

    chan3 := make(chan string, 2)

    wg.Add(1)

    go makeChanStr("yeye", chan1, chan3)

    wg.Add(1)

    go makeChanStr("okok", chan2, chan3)

    wg.Wait()

    close(chan3)

    println(<-chan1)

    println(<-chan2)

    for chs := range chan3 {

         println(chs)

    }

}


func makeChanStr(s string, c1 chan string, c2 chan string) {

    defer wg.Done()


    c1 <- "get " + s

    c2 <- "same value"

    fmt.Printf("execute ok %s", s)

}

Stackoverflow只是不让我提交问题.......所以我只需要添加一些文本.....


哆啦的时光机
浏览 78回答 2
2回答

月关宝盒

主块 on ,等待这两个 go 例程完成(因为 和wg.Wait()wg.Add(1)wg.Done())go makeChanStr("yeye", chan1, chan3)go makeChanStr("okok", chan2, chan3)但是它们阻塞(或),因为它是一个无缓冲信道。chan1chan2chan1 := make(chan string)尝试更改 和 缓冲通道:chan1chan2chan1 := make(chan string,1)chan2 := make(chan string,1)

白猪掌柜的

此代码在主 goroutine 中阻止,并在 worker 中写入。为了避免这种情况 - 从和之前读取,从而取消阻止工作线程,并且他们不会阻止写入缓冲。因此,将调用并且不会阻止主goroutine。wg.Wait()c1c1c2wg.Wait()c3wg.Done()wg.Wait()package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sync")var wg sync.WaitGroupfunc main() {&nbsp; &nbsp; chan1 := make(chan string)&nbsp; &nbsp; chan2 := make(chan string)&nbsp; &nbsp; chan3 := make(chan string, 2)&nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; go makeChanStr("yeye", chan1, chan3)&nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; go makeChanStr("okok", chan2, chan3)&nbsp; &nbsp; println(<-chan1)&nbsp; &nbsp; println(<-chan2)&nbsp; &nbsp; wg.Wait()&nbsp; &nbsp; close(chan3)&nbsp; &nbsp; for chs := range chan3 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;println(chs)&nbsp; &nbsp; }}func makeChanStr(s string, c1 chan string, c2 chan string) {&nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; c1 <- "get " + s&nbsp; &nbsp; c2 <- "same value"&nbsp; &nbsp; fmt.Printf("execute %s\n", s)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go