本文介绍了去项目的主要门房睡眠永远?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 是否有任何API让 main goroutine永远睡眠? 换句话说,我希望我的项目一直运行,除非我停止它。解决方案 睡觉 您可以使用大量的构造,永远阻止您的CPU吃东西。 例如,一个选择,但不包含任何个案(且没有 default $ p $ select {} 或从一个没有人发送任何内容的频道接收: < - make(chan int) 或从> nil < ;-( chan int)(nil) 频道发送也会永远阻止: $ b $ b (chan int)(nil) 或锁定一个已经锁定的 sync.Mutex : mux:= sync.Mutex {} mux.Lock() mux.Lock() 退出 如果您确实想要提供一种退出的方式,一个简单的渠道可以做到这一点。提供退出频道,并从中接收。当你想退出时,关闭 quit 通道,因为一个关闭通道上的接收操作总是可以立即进行,产生元素类型的零值。 var quit = make(chan struct {}) func main(){ //启动代码... //然后阻塞(等待退出信号): } //在另一个goroutine中,如果你想退出: close(quit) 请注意,发出关闭(退出)可能会终止您的应用任何时候。引用规范:程序执行: 程序执行首先初始化主包,然后调用函数 main 。当该函数调用返回时,程序退出。 它不会等待其他(非主要)goroutine完成。 当执行 close(quit)时,我们的 main()函数可以继续执行,这意味着 main goroutine可以返回,所以程序退出。 Is there any API to let the main goroutine sleep forever? In other words, I want my project always run except when I stop it. 解决方案 "Sleeping"You can use numerous constructs that block forever without "eating" up your CPU.For example a select without any case (and no default):select{}Or receiving from a channel where nobody sends anything:<-make(chan int)Or receiving from a nil channel also blocks forever:<-(chan int)(nil)Or sending on a nil channel also blocks forever:(chan int)(nil) <- 0Or locking an already locked sync.Mutex:mux := sync.Mutex{}mux.Lock()mux.Lock()QuittingIf you do want to provide a way to quit, a simple channel can do it. Provide a quit channel, and receive from it. When you want to quit, close the quit channel as "a receive operation on a closed channel can always proceed immediately, yielding the element type's zero value after any previously sent values have been received".var quit = make(chan struct{})func main() { // Startup code... // Then blocking (waiting for quit signal): <-quit}// And in another goroutine if you want to quit:close(quit)Note that issuing a close(quit) may terminate your app at any time. Quoting from Spec: Program execution: Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete.When close(quit) is executed, the last statement of our main() function can proceed which means the main goroutine can return, so the program exits. 这篇关于去项目的主要门房睡眠永远?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-21 02:10