WaitGroup elegant exit

WaitGroup provides three methods to achieve elegant exit

1, Add (): for each received http / mq request, the counter will + 1'd
2, the Done (): each executing the http / mq request, the counter will -1
. 3, the Wait (): Counter = 0, i.e., no request is being processed

import "sync"
import "os/signal"
import "fmt"

func main() {
	var wg sync.WaitGroup
	sig := make(chan os.Signal, 1)
    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	httpHandle()
	
	go func() {
		sig := <-sig
		wg.Wait()
		done <- true
	}()
	
	<-done
	fmt.println("quit success")
}

func httpHandle() {
	wg.Add()
	defer wg.Done()
	xxx     
}

parameter represents signal.Notify registered to receive the signal: no signal parameter indicates receive all signals
syscall.SIGINT: receiving a + c Ctrl
syscall.SIGTERM: quits

PS: If the process is stopped by supervisor signal, the essence do is kill -9 xxx, if the execution time of the program will wait too long card is forced to exit

Published 171 original articles · won praise 72 · views 8851

Guess you like

Origin blog.csdn.net/ambzheng/article/details/104067469