Ultra-simple co-synchronization tool in Golang

Source: Internet
Author: User

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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.