"all goroutines are asleep – deadlock! Exit status 2" error in a printer-receiver program

huangapple go评论70阅读模式
英文:

"all goroutines are asleep - deadlock! Exit status 2" error in a printer-receiver program

问题

我正在尝试创建一个简单的程序来学习Go中的通道。
但是我遇到了一个死锁错误,我无法解决。

package main

import (
	"fmt"
	"time"
)

func printer(c chan int) {
	for i := 0; i < 10; i++ {
		c <- i
		time.Sleep(time.Second)
	}
}

func reciever(c chan int) {
	for {
		recievedMsg := <-c
		fmt.Println(recievedMsg)
	}
}

func main() {
	newChanel := make(chan int)
	printer(newChanel)
	reciever(newChanel)
}

我的初步想法是与Sleep函数有关,但即使我不包括它,我仍然遇到这个错误和退出消息。
有人可以给一些解决这个问题的提示吗?

提前感谢。

英文:

I am trying to create a simple program to learn channels in Go.
But I´m running in to a deadlock error, which I can´t figure out

package main

import (
	&quot;fmt&quot;
	&quot;time&quot;
)

func printer(c chan int) {
	for i := 0; i &lt; 10; i++ {
		c &lt;- i
		time.Sleep(time.Second)
	}
}

func reciever(c chan int) {
	for {
		recievedMsg := &lt;-c
		fmt.Println(recievedMsg)
	}
}

func main() {
	newChanel := make(chan int)
	printer(newChanel)
	reciever(newChanel)
}

My initial thoughts was something about the Sleep function, but even if I don´t include this I still run into this error and exit message.
Can anyone give some hints on how to solve this?

Thanks in advance

答案1

得分: 8

你需要两个执行线程,因为现在没有办法调用reciever函数,因为你从未离开printer函数。你需要在一个单独的goroutine上执行其中一个。

你还应该close通道并在循环中使用range操作符,这样当通道关闭时循环会结束。

所以我建议你使用以下代码:

func printer(c chan int) {
    for i := 0; i < 10; i++ {
        c <- i
        time.Sleep(time.Second)
    }
    close(c)
}

func reciever(c chan int) {
    for recievedMsg := range c {
        fmt.Println(recievedMsg)
    }
}

func main() {
    newChanel := make(chan int)
    go printer(newChanel)
    reciever(newChanel)
}
英文:

You need two execution threads because now there is no way for the reciever function to be called as you never leave the printer function. You need to execute one of them on a separate goroutine.

You should also close the channel and use the range operator in your loop, so that it ends when the channel is closed.

So I propose you this code :

func printer(c chan int) {
	for i := 0; i &lt; 10; i++ {
		c &lt;- i
		time.Sleep(time.Second)
	}
	close(c)
}

func reciever(c chan int) {
	for recievedMsg := range c {
		fmt.Println(recievedMsg)
	}
}

func main() {
	newChanel := make(chan int)
	go printer(newChanel)
	reciever(newChanel)
}

huangapple
  • 本文由 发表于 2012年9月12日 23:14:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/12391371.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定