douye9175 2016-09-19 14:51
浏览 8
已采纳

使用golang频道。 获得“所有goroutine都在睡觉-死锁!”

iam currently playing around with go routines, channels and sync.WaitGroup. I know waitgroup is used to wait for all go routines to complete based on weather wg.Done() has been called enough times to derement the value set in wg.Add(). i wrote a small bit of code to try to test this in golang playground. show below

var channel chan int
var wg sync.WaitGroup


func main() {

  channel := make(chan int)
  mynums := []int{1,2,3,4,5,6,7,8,9} 
  wg.Add(1)

  go addStuff(mynums)
  wg.Wait()
  close(channel)
  recieveStuff(channel)
 }

 func addStuff(mynums []int) {

   for _, val := range mynums {
       channel <- val
   }
   wg.Done()
 }

 func recieveStuff(channel chan int) {
    for val := range channel{
    fmt.Println(val)
 }
} 

Iam getting a deadlock error. iam trying to wait on the routing to return with wg.Wait()? then, close the channel. Afterwards, send the channel to the recievestuff method to output the values in the slice? but it doesnt work. Ive tried moving the close() method inside the go routine after the loop also as i thought i may of been trying to close on the wrong routine in main(). ive found this stuff relatively confusing so far coming from java and c#. Any help is appreciated.

  • 写回答

1条回答 默认 最新

  • douhulao7642 2016-09-19 15:01
    关注

    The call to wg.Wait() wouldn't return until wg.Done() has been called once.

    In addStuff(), you're writing values to a channel when there's no other goroutine to drain those values. Since the channel is unbuffered, the first call to channel <- val would block forever, resulting in a deadlock.

    Moreover, the channel in addStuff() remains nil since you're creating a new variable binding inside main, instead of assigning to the package-level variable. Writing to a nil channel blocks forever:

    channel := make(chan int) //doesn't affect the package-level variable

    Here's a modified example that runs to completion by consuming all values from the channel:

    https://play.golang.org/p/6gcyDWxov7

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置