Ultra-simple co-synchronization tool in Golang
Image
Starting from demand
Now there are requirements: multi-process processing of a batch of data, but need to run all the process to continue to the next step, this requirement is very common in daily processing data. Multi-process can squeeze CPU and IO to the maximum, but from a business point of view, need to maintain consistency, this time we need to co-synchronization technology.
Flowchart Solution
It can be seen that the time in the 3 run is not controllable, but in order to achieve the purpose of synchronization, it is necessary to wait for 3 Ctrip to complete the following process.
Image
Solution
Golang provides a very handy package sync.waitgroup
that provides 3 ways to
Add(delta int)
Add Ctrip Record
Done()
Remove Ctrip Records
Wait()
All Ctrip is waiting for all records to end.
Code
package main import ( "fmt" "sync" "time") var wg sync.WaitGroup func main() { for i := 0; i < 3; i++ { wg.Add(1) //创建一个协程,记录一次 go worker(i) } wg.Wait() //同步等待所有的协程全部执行完成 fmt.Println("All done !")}func worker(i int) { fmt.Println(i) time.Sleep(time.Second * time.Duration(i)) wg.Done() //携程结束,从记录中移除等同于Add(-1)}
Output:
210All done !
Image