Sobes.tech
Middle

What is a Mutex?

sobes.tech AI

Answer from AI

Mutex (mutual exclusion) is a synchronization mechanism in Go used to prevent multiple goroutines from accessing shared resources simultaneously, such as variables or data structures. Mutex ensures that only one goroutine can hold the lock and execute the critical section of code at any given time.

Example of using sync.Mutex in Go:

import (
    "fmt"
    "sync"
)

func main() {
    var mu sync.Mutex
    counter := 0

    increment := func() {
        mu.Lock()           // acquire lock
        defer mu.Unlock()   // release lock
        counter++
    }

    var wg sync.WaitGroup
    for i := 0; i < 1000; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            increment()
        }()
    }
    wg.Wait()
    fmt.Println("Counter:", counter)
}

Without Mutex, the result could be incorrect due to data races.

What is a Mutex? — Golang - sobes.tech