英文:
Why is the following code sample stuck after some iterations?
问题
我正在学习Go语言,并且遇到了一段代码,不明白为什么它在一段时间后会停止运行。
package main
import "log"
func main() {
deliveryChann := make(chan bool, 10000)
go func() {
for {
deliveryChann <- true
log.Println("Sent")
}
}()
go func() {
for {
select {
case <-deliveryChann:
log.Println("received")
}
}
}()
go func() {
for {
select {
case <-deliveryChann:
log.Println("received")
}
}
}()
go func() {
for {
select {
case <-deliveryChann:
log.Println("received")
}
}
}()
for {
}
}
这是一个简单的开始,用于调查问题。
英文:
I am trying to learn golang and i got a little piece of code that i do not understand why it gets stuck after some time.
package main
import "log"
func main() {
deliveryChann := make(chan bool, 10000)
go func() {
for {
deliveryChann <- true
log.Println("Sent")
}
}()
go func() {
for {
select {
case <-deliveryChann:
log.Println("received")
}
}
}()
go func() {
for {
select {
case <-deliveryChann:
log.Println("received")
}
}
}()
go func() {
for {
select {
case <-deliveryChann:
log.Println("received")
}
}
}()
for {
}
}
An basic start on how to investigate would suffice.
答案1
得分: 2
主要的goroutine(运行for {}
循环的那个)占用了线程,其他的goroutine无法执行。如果你将main
函数的结尾改为:
for {
runtime.Gosched()
}
那么线程将被释放,另一个goroutine将被激活。
func Gosched()
Gosched让出处理器,允许其他的goroutine运行。它不会挂起当前的goroutine,所以执行会自动恢复。
-- https://golang.org/pkg/runtime/#Gosched
英文:
The main goroutine (running the for {}
loop) is hogging the thread, and none of the other goroutines are able to execute because of it. If you change the end of your main
function to:
for {
runtime.Gosched()
}
then the thread will be released and another goroutine made active.
> func Gosched()
>
> Gosched yields the processor, allowing other goroutines to run. It does not suspend the current goroutine, so execution resumes automatically.
答案2
得分: 0
执行goroutine的顺序是不确定的。代码被卡住是合法的。你可以通过与main()
进行通信来更加确定性。例如,将以下代码放在main()
中而不是go func()
中:
for {
deliveryChann <- true
log.Println("Sent")
}
英文:
Order of execution of goroutings is undefined. Code gets stuck is legal. You can be more deterministic doing communication with main()
. For example place
for {
deliveryChann <- true
log.Println("Sent")
}
in main()
instead of go func()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论