当前位置:网站首页>Go language - use of goroutine coroutine

Go language - use of goroutine coroutine

2022-06-24 14:21:00 Crying while learning

Preface

         Synergetic English coroutine,go The co process in language is goroutine.Go It's a concurrent language , Not parallel languages .

        go The creation of language collaboration is very simple , Just add... To the front of the called function go keyword , The program will run a new goroutine.

         however goroutine There is no return value , The return value is ignored . Therefore, it is often necessary to pass channel Conduct goroutine Communication between .

goroutine Use

func main() {
	go mytest()
	for i := 0; i < 100; i++ {
		fmt.Println(" The main function outputs :", i)
	}
}

func mytest() {
	for i := 0; i < 500; i++ {
		fmt.Println("goroutine Output numbers in :", i)
	}
}

Output through this simple example , Can sum up goroutine Two characteristics of :

  1. goroutine The execution of the function in the coroutine and the execution of the main function are simultaneous , The output is alternating .
  2. After the main program , Even son goroutine Not done , It will also end with the main program .

sync package -WaitGroup

         In general , After the main program , Son goroutine Will be over .

         In order to make the main program wait for the sub groutine Execution completed , One way is to use sleep. however sleep There is a problem , We have no way to know goroutine The specific length of time to execute , Only try to lengthen it sleep Time for .

        So we can use sync Bag WaitGroup Solve the problem that the main process waits for children goroutine The problem of .

var wg sync.WaitGroup

func main() {
	wg.Add(1) // Definition WaitGroup The queue length , The length is 1
	go mytest()
	for i := 0; i < 100; i++ {
		fmt.Println(" The main function outputs :", i)
	}
	wg.Wait() // At the end of the main program , wait for WaitGroup The queue is 0 And then exit 
}

func mytest() {
	for i := 0; i < 500; i++ {
		fmt.Println("goroutine Output numbers in :", i)
	}
	wg.Done() // amount to wg.Add(-1), One goroutine end , call wg.Done(), Queue minus one 
}

wg.Add(1)        Main function , Definition WaitGroup The queue length

wg.Done()        Son goroutine in , The function finally calls , Is equivalent to WaitGroup The queue length -1

wg.Wait()        Main function , At the end of the main function , wait for WaitGroup The queue length is 0

原网站

版权声明
本文为[Crying while learning]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241237270422.html