英文:
How do I block the program / goroutine?
问题
我有一个程序,它会启动两个goroutine在后台提供服务。然后,我想阻塞主goroutine并让它们在后台运行。我想要永远阻塞,并且不关心干净的退出。我应该如何做到这一点?我可以等待通道,然后永远不向其中发送任何内容。我可以在循环中睡眠。但是,这两种方法都不太合适。我想知道是否有一个更简单的block()
函数可以调用?
我目前正在这样做:
var i chan int
<-i
英文:
I have a program that fires off two goroutines that provide services in the background. I then want to block the main goroutine and let them run in the background. I want to block 'forever' and I don't care about clean exits. How should I do this? I could wait on channel and then never send anything down it. I could sleep in a loop. Neither feels quite right I thought there might be a simpler block()
function I could call?
I'm currently doing this
var i chan int
<-i
答案1
得分: 5
你可以使用sync.WaitGroup
,将其传递给每个goroutine。这是等待调用goroutine的常见方式,等待其子goroutine完成。
然而,在你的情况下,如果你不关心结果,也可以这样做:
select {}
根据select
的规范:
> 如果没有非nil通道的情况,该语句将永远阻塞
这个语句会永远阻塞,同时将控制权交给其他的goroutine。
英文:
You can use a sync.WaitGroup
which you pass to each of your goroutine. This is the common way
to wait in the calling goroutine for its children.
However, in your case where you don't care for the results this should do as well:
select {}
From the spec regarding select
:
> If there are no cases with non-nil channels, the statement blocks forever
This statement blocks forever while yielding control to the other goroutines.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论