Mutex in Go

Go: Mutex

A mutex (short for "mutual exclusion") is a synchronization primitive that allows you to protect shared resources from concurrent access by multiple goroutines. A mutex has two states: locked and unlocked. When a mutex is locked, any goroutine that attempts to lock it will block until the mutex is unlocked. When a mutex is unlocked, the next goroutine that attempts to lock it will succeed and continue running.

How to use a mutex in Go

Here's an example of how you might use a mutex in Go to protect access to a shared variable:


    package main

    import (
        "fmt"
        "sync"
    )

    var (
        count int
        mutex sync.Mutex
    )

    func increment() {
        mutex.Lock()
        count++
        mutex.Unlock()
    }

    func main() {
        var wg sync.WaitGroup
        for i := 0; i < 1000; i++ {
            wg.Add(1)
            go func() {
                defer wg.Done()
                increment()
            }()
        }
        wg.Wait()
        fmt.Println("Final count:", count)
    }
  • In above example, we have a count variable that is shared among multiple goroutines. We use a mutex to protect access to the count variable, so that only one goroutine can access it at a time.
  • The increment function acquires the mutex by calling mutex.Lock(), increments the count variable, and then releases the mutex by calling mutex.Unlock().
  • The main function creates 1000 goroutines, each of which calls increment, and then waits for all of them to finish before printing the final value of count.

Using a mutex in this way ensures that the count variable is incremented atomically, meaning that there are no race conditions or other synchronization issues that could cause the final value of count to be incorrect.

Previous Article

Next Article