Search code examples
goconcurrencymutex

Mutex does not seem to be locking properly


I am just learning about mutexess. I thought the following program would return a total of 1000, but I am getting varied results, so I assume I am doing something wrong...

package main

import (
    "fmt"
    "sync"
)

var total int
var locker sync.RWMutex

func add() {
    for x := 1; x <= 100; x++ {
        locker.Lock()
        total += 1
        locker.Unlock()
    }
}

func main() {
    for x := 1; x <= 10; x++ {
        go add()
    }
    fmt.Printf("Total is %v\n", total)
}

Solution

  • Main function returns before gorutines finished their works, you should add sync.WaitGroup, this code works as you expected: https://play.golang.com/p/_OfrZae0soB

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    var total int
    var locker sync.RWMutex
    
    func add(wg *sync.WaitGroup) {
        defer wg.Done()
        for x := 1; x <= 100; x++ {
            locker.Lock()
            total += 1
            locker.Unlock()
        }
    }
    
    func main() {
        var wg sync.WaitGroup
        for x := 1; x <= 10; x++ {
            wg.Add(1)
            go add(&wg)
        }
        wg.Wait()
        fmt.Printf("Total is %v\n", total)
    }