如何阻塞程序/协程?

huangapple go评论78阅读模式
英文:

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
&lt;-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.

huangapple
  • 本文由 发表于 2013年9月13日 02:46:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/18772091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定