Goroutine synchronization with Mutex

Viewed 48
    var n int32 = 0
    var mutex *sync.Mutex = new(sync.Mutex)

    for i := 0; i < 100000; i++ {
        go func() {
            mutex.Lock()
            defer mutex.Unlock()
            atomic.AddInt32(&n, 1)

        }()
    }

    fmt.Println(n)

I'm wondering why the result of n is not 100000, looks like the mutex lock does not work.

1 Answers

fmt.Println(n) is executing before the go threads completion,You need to add the time.Sleep(5 * time.Millisecond) before fmt.Println(n) like below

   package main
    
    import (
        "fmt"
        "sync"
        "sync/atomic"
        "time"
    )
    
    func main() {
        var n int32 = 0
        var mutex *sync.Mutex = new(sync.Mutex)
    
        for i := 0; i < 100000; i++ {
            go func() {
                mutex.Lock()
                defer mutex.Unlock()
                atomic.AddInt32(&n, 1)
    
            }()
        }
        time.Sleep(5 * time.Millisecond)
        fmt.Println(n)
    }
Output :
--------
100000

Or

package main

import (
    "fmt"
    "sync"
    "sync/atomic"
)

func main() {
    var n int32 = 0
    var mutex *sync.Mutex = new(sync.Mutex)
    var wg sync.WaitGroup

    for i := 0; i < 100000; i++ {
        wg.Add(1)
        go func() {
            mutex.Lock()
            defer mutex.Unlock()
            atomic.AddInt32(&n, 1)
            wg.Done()

        }()
    }
    wg.Wait()
    fmt.Println(n)
}

Output :
--------
100000
Related