当前位置:网站首页>Go synchronization waiting group

Go synchronization waiting group

2022-06-25 02:40:00 Pumpkin head 777

Go In addition to using channels in language (channel) And mutex for synchronization between two concurrent programs , You can also use wait groups to synchronize multiple tasks , Waiting group can ensure that a specified number of tasks can be completed in a concurrent environment

stay sync.WaitGroup( Waiting group ) Type in the , Every sync.WaitGroup Value internally maintains a count , The initial default value for this count is zero .

package main

import (
	"fmt"
	"sync"
	"time"
)

var wg sync.WaitGroup // Define a synchronization waiting group 
func task(i int) {
    
	fmt.Println("task...", i)
	// Time consuming operational tasks , Network request , Read the file 
	time.Sleep(time.Second)
	wg.Done() // Subtract a count 
}
func main() {
    
	for i := 0; i < 10; i++ {
    
		wg.Add(1) // Add a count 
		go task(i)
	}
	wg.Wait() // Block until all tasks are completed 
	fmt.Println("over")
}
原网站

版权声明
本文为[Pumpkin head 777]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206242312223463.html