This is a creation in Article, where the information may have evolved or changed.
The current design of the go runtime assumes that the programmer is responsible for detecting when to terminate a goroutine and when to terminate the program. Can be called by the OS. Exit or return from the main () function to terminate the program in the normal manner. And sometimes what we need is to make the program block in this line.
Use Sync. Waitgroup
Wait until Waitgroup equals 0.
package mainimport "sync"func main() { var wg sync.WaitGroup wg.Add(1) wg.Wait()}
Empty Select
select{} is a select without any case, it will always block
package mainfunc main() { select{}}
Dead loop
Although it can block, it will occupy a CPU 100%. Do not recommend using
package mainfunc main() { for {}}
Use Sync. Mutex
A lock that has been locked, locked again will be blocked, this is not recommended to use
package mainimport "sync"func main() { var m sync.Mutex m.Lock() m.Lock()}
Os. Signal
System semaphore, which is also a channel in go, blocking until a specific message is received
package mainimport ( "os" "syscall" "os/signal")func main() { sig := make(chan os.Signal, 2) signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT) <-sig}
Empty channel or nil channel
The channel is blocked until the message is received, and the nil channel is blocked forever.
package mainfunc main() { c := make(chan struct{}) <-c}
package mainfunc main() { var c chan struct{} //nil channel <-c}
Summarize
Note that most of the code written above cannot be run directly, it will be panic, "all Goroutines is asleep-deadlock!", because go runtime will check all your goroutine are stuck, no one to execute. You can add one or more goroutine to your own business logic in front of the blocking code, so you won't be deadlock.
Reference
http://pliutau.com/different-ways-to-block-go-runtime-forever/