Golang sync. Waitgroup Resolving Goroutine Synchronization

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

go provides sync packet and channel to resolve synchronization and communication . The novice is more likely to create deadlocks for channel channels, and if the buffered channel also takes into account the rate at which the channel is put in and out of the data.
Literally can understand, sync. Waitgroup is waiting for a group of threads to end. It implements a similar task queue structure where you can add tasks to the queue, remove the task from the queue when the task is complete, and if the tasks in the queue are not all complete, the queue will trigger blocking to prevent the program from continuing to run.
sync. Waitgroup has only 3 methods, ADD (), Done (), Wait (). where done () is the alias of Add (-1). Simply put, using Add () adds a count, done () minus a count, the count is not 0, and the wait () is blocked from running.
A simple example is as follows:

package main import ("fmt""sync") var waitgroup sync.WaitGroup func test(shownum int) {fmt.Println(shownum)waitgroup.Done() //任务完成,将任务队列中的任务数量-1,其实.Done就是.Add(-1)} func main() {for i := 0; i < 10; i++ {waitgroup.Add(1) //每创建一个goroutine,就把任务队列中任务的数量+1go test(i)}waitgroup.Wait() //.Wait()这里会发生阻塞,直到队列中所有的任务结束就会解除阻塞fmt.Println("done!")}

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.