英文:
"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 (
"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)
}
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 < 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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论