go in WaitGroup

wait_group

sync.WaitGroup type is complicated by security, but also be able to use out of the box. A method of this type has three hands, namely: Add, Done, and Wait.

sync.WaitGroup is a structure type. Wherein a byte array representative of the type of field count, this field is represented by 4 bytes of a given count, waiting for another 4 byte count. When a variable is declared sync.WaitGroup type, wherein these two counts would be 0. Which may increase or decrease by a given counting add method, for example:

wg.Add(3)
or
wg.Add(-3)
Note that we can not let this count value becomes a negative number.
wg.Done()

Equivalent to

wg.Add(-1)

We know that the method can be done to change and add value of the counter, but what specific role changed after it?

When calling Wait method sync.WaitGroup type value, it will check the given count. If the count is 0, then the method returns immediately and does not have any impact on the program. However, if the counter is greater than 0, the method calls that goroutine where it will block while waiting for the counter is incremented. When done add or until a method is called the value of a given count back to 0. This value will therefore wait to wake up and blocked all goroutine, while clearing the wait count.

Now we have a case: Suppose program enabled 4 goroutine, respectively g1, g2, g3, g4. Which g2, g3, g4 is enabled by the code of g1, g1 is enabled and then wait for the completion of these special tasks.

Use channel for blocking

  sign := make(chan int, 3)
    go func() {
        sign <- 2
        fmt.Println(2)
    }()
    go func() {
        sign <- 3
        fmt.Println(3)
    }()

    go func() {
        sign <- 4
        fmt.Println(4)
    }()

    for i := 0; i < 3; i++ {
        fmt.Println ( " execution " , <- Sign)
    }
Use the channel are too heavy, and in principle, we should not channel as a mutex or semaphores to use.

Use waitGroup

var wg sync.WaitGroup

    wg.Add(3)
    go func() {
        wg.Done()
        fmt.Println(2)
    }()
    go func() {
        wg.Done()
        fmt.Println(3)
    }()
    go func() {
        wg.Done()
        fmt.Println(4)
    }()

    wg.Wait()
    fmt.Println("1 2 3 4 end")

  

Reference: go Concurrent become real

 

Guess you like

Origin www.cnblogs.com/ricklz/p/12020674.html