英文:
How to get a Go program to block forever
问题
我正在尝试让我的Go程序永远阻塞,但是没有任何效果。
以下是我尝试过的一些方法:
package main
func main() {
select{}
}
和
package main
func main() {
ch := make(chan bool)
<-ch
}
和
package main
import "sync"
func main() {
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
}
每次我都会得到相同的错误:fatal error: all goroutines are asleep - deadlock!
我记得以前我很容易就能做到这一点。我能让Go程序永远阻塞吗?
英文:
I am trying to get my Go program to block forever, but nothing is working.
Here are some things I have tried:
package main
func main() {
select{}
}
and
package main
func main() {
ch := make(chan bool)
<-ch
}
and
package main
import "sync"
func main() {
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
}
Each time I get the same error: fatal error: all goroutines are asleep - deadlock!
I thought I have done this before easily. Am I able to get the go program to block forever?
答案1
得分: 4
那些方法只有在你创建了另一个 goroutine(除了阻塞之外还做其他事情)时才有效。
解决你问题的即时方法是:
这将休眠大约300年。
英文:
Those methods would work if you spawned another goroutine (which was doing stuff other than blocking)
The immediate fix to your problem would be:
which would sleep for ~300 years
答案2
得分: 3
例如,main
goroutine 永远阻塞的情况下,
package main
import (
"fmt"
"time"
)
func forever() {
for {
fmt.Println(time.Now().UTC())
time.Sleep(time.Second)
}
}
func main() {
go forever()
select {} // 永远阻塞
}
输出结果:
2017-08-05 02:50:10.138353286 +0000 UTC
2017-08-05 02:50:11.138504194 +0000 UTC
2017-08-05 02:50:12.138618149 +0000 UTC
2017-08-05 02:50:13.138753477 +0000 UTC
2017-08-05 02:50:14.13888856 +0000 UTC
2017-08-05 02:50:15.139027355 +0000 UTC
...
...
...
英文:
For example, the main
goroutine blocks forever,
package main
import (
"fmt"
"time"
)
func forever() {
for {
fmt.Println(time.Now().UTC())
time.Sleep(time.Second)
}
}
func main() {
go forever()
select {} // block forever
}
Output:
2017-08-05 02:50:10.138353286 +0000 UTC
2017-08-05 02:50:11.138504194 +0000 UTC
2017-08-05 02:50:12.138618149 +0000 UTC
2017-08-05 02:50:13.138753477 +0000 UTC
2017-08-05 02:50:14.13888856 +0000 UTC
2017-08-05 02:50:15.139027355 +0000 UTC
...
...
...
答案3
得分: 1
对于问题“如何使Go程序永远阻塞”,已经有使用for循环或time.Sleep
的答案。
但我想回答的是“如何使Go程序永远阻塞_而通道永远不接收值_”。
package main
func main() {
ch := make(chan bool)
go func(c chan bool) {
for {
}
c <- true // 因为c永远不会接收到true,
}(ch)
<-ch // 因此ch将永远等待。
}
我认为上面的示例代码可以帮助理解为什么以及何时Go程序会被通道阻塞。
英文:
For the question "How to get a Go program to block forever" there's already answers that use a for loop or time.Sleep
.
But I want to answer "How to get a Go program to block forever with a channel never receives a value".
package main
func main() {
ch := make(chan bool)
go func(c chan bool) {
for {
}
c <- true // Because c never receives true,
}(ch)
<-ch // thus ch waits forever.
}
I think the sample code above can help to understand why and when a Go program will block by a channel.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论