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

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

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?