Golang Sync Waitgroup

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

Just looked at Golang's sync bag and saw a very useful feature. 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

Package Mainimport ("FMT" "Sync" "Time") Func main () {var wg sync. Waitgroupfor I: = 0; I < 5; i = i + 1 {WG. ADD (1) go func (n int) {//Defer WG. Done () defer WG. ADD ( -1) echonumber (n)} (i)}WG. Wait ()}func echonumber (i int) {time. Sleep (3e9) fmt. Println (i)}

Output Result:
01234
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.



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.