Golang in the waitgroup of the Sync pack

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The sync pack in Golang has a very useful function, which is Waitgroup

Let's talk about the purpose of Waitgroup: it can wait until all the goroutine execute, and block the execution of the main thread until all the Goroutine execution is complete.

Waitgroup a total of three methods: ADD (delta int), done (), Wait (). Simply say the effect of these three methods.

Add: Adds or reduces the number of waiting goroutine

Done: Equivalent to add (-1)

Wait: Perform blocking until all the Waitgroup number becomes 0

Take a look at the example:

Package Mainimport ("FMT"    "Sync"    " Time") Func main () {varWG Sync. Waitgroup forI: =0; I <5; i = i +1{WG. ADD (1) go func (nint) {            //defer WG. Done ()Defer WG. ADD (-1) Echonumber (n)} (i)} WG. Wait ()}func echonumber (iint) {time. Sleep (3e9) fmt. Println (i)}

The results are as follows:

0 1 2 3 4

The program is simple, just output the number of each loop over 3 seconds. Then, if the program does not waitgroup, then the output will not be visible. Because the Goroutine has not finished, the main thread has been executed. Note the defer WG. Done () and defer WG. ADD (-1) acts the same. This is good, the original execution script, all use time. Sleep, with an estimated time until the child thread finishes executing. Waitgroup is very good. Although Chanel can be implemented, it feels good if it involves not having a child thread synchronizing with the main thread data.

 

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.