英文:
golang: all goroutines are asleep - deadlock
问题
我想使用两个goroutine打印1到100:
package main
import (
"fmt"
"sync"
)
var my_chan chan int
var wg sync.WaitGroup
func worker() {
for true {
number := <-my_chan
fmt.Println(number)
number++
if number > 100 {
wg.Done()
return
}
my_chan <- number
}
}
func main() {
wg.Add(2)
my_chan := make(chan int)
init_num := 1
go worker()
go worker()
my_chan <- init_num
wg.Wait()
}
当我运行上述代码时,我得到以下错误:
fatal error: all goroutines are asleep - deadlock!
有人能告诉我我做错了什么吗?
英文:
I want to print 1 to 100 use two goroutine:
package main
import (
"fmt"
"sync"
)
var my_chan chan int
var wg sync.WaitGroup
func worker() {
for true {
number := <-my_chan
fmt.Println(number)
number++
if number > 100 {
wg.Done()
return
}
my_chan <- number
}
}
func main() {
wg.Add(2)
my_chan := make(chan int)
init_num := 1
go worker()
go worker()
my_chan <- init_num
wg.Wait()
}
When I run the above code, I get the following error:
fatal error: all goroutines are asleep - deadlock!
Can anyone tell me where I am doing wrong?
答案1
得分: 2
将通道的创建替换为以下代码:
my_chan := make(chan int)
否则,在主函数中重新声明my_chan
,并且所有的goroutine都会尝试从一个空通道中读取。这将导致阻塞。
然后它将计数到100并发生死锁。对于其中一个goroutine,检查数字是否大于100将起作用,而另一个goroutine将被阻塞等待读取/写入操作。
英文:
Replace the channel creation with this:
my_chan = make(chan int)
Otherwise you are redeclaring my_chan
in main, and all goroutines try to read from a nil channel. That will block.
Then it will count to 100 and deadlock. The check for number being larger than 100 will work for one of the goroutines, while the other one will be stuck waiting to read/write.
答案2
得分: 0
感谢Burak Serdar的答案,以下代码有效:
package main
import (
"fmt"
"sync"
)
var my_chan chan int
var wg sync.WaitGroup
func worker() {
for true {
number := <-my_chan
if number > 100 {
wg.Done()
my_chan <- 101
return
}
fmt.Println(number)
number++
my_chan <- number
}
}
func main() {
wg.Add(2)
my_chan = make(chan int)
init_num := 1
go worker()
go worker()
my_chan <- init_num
wg.Wait()
}
英文:
Thanks for Burak Serdar's answer, the following code works:
package main
import (
"fmt"
"sync"
)
var my_chan chan int
var wg sync.WaitGroup
func worker() {
for true {
number := <-my_chan
if number > 100 {
wg.Done()
my_chan <- 101
return
}
fmt.Println(number)
number++
my_chan <- number
}
}
func main() {
wg.Add(2)
my_chan = make(chan int)
init_num := 1
go worker()
go worker()
my_chan <- init_num
wg.Wait()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论