74

在Golang中各种永远阻塞的姿势

 5 years ago
source link: https://sheepbao.github.io/post/golang_diff_ways_block_forever/?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
在Golang中各种永远阻塞的姿势 Go的运行时的当前设计,假定程序员自己负责检测何时终止一个goroutine以及何时终止该程序。 可以通过调用os.Exit或从main()函数的返回来以正常方式终止程序。而有时候我们需要的是使程序阻塞在这一行。使用sync.WaitGroup 一直等待直到WaitGroup等于0package main import "sync" func main() { var wg sync.WaitGroup wg.Add(1) wg.Wait() } 空select select{}是一个没有任何case的select,它会一直阻塞package main func main() { select{} } 死循环 虽然能阻塞,但会100%占用一个cpu。不建议使用package main func main() { for {} } 用sync.Mutex 一个已经锁了的锁,再锁一次会一直阻塞,这个不建议使用package main import "sync" func main() { var m sync.Mutex m.Lock() m.Lock() } os.Signal 系统信号量,在go里面也是个channel,在收到特定的消息之前一直阻塞package main import ( "os" "syscall" "os/signal" ) func main() { sig := make(chan os.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK