Sobes.tech
Junior — Middle

How is mutual exclusion implemented using Mutex in Go language?

sobes.tech AI

Answer from AI

In the Go language, the sync.Mutex type is used to implement mutual exclusion (mutex). It allows protecting critical sections of code from concurrent access by multiple goroutines, preventing race conditions.

Main operations:

  • Lock() — acquires the mutex, blocking other goroutines.
  • Unlock() — releases the mutex, allowing other goroutines to continue.

Example of usage:

package main

import (
    "fmt"
    "sync"
)

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

    mu.Lock() // Acquire the mutex
    counter++
    fmt.Println("Counter:", counter)
    mu.Unlock() // Release the mutex
}

In a multithreaded environment, the mutex guarantees that only one goroutine executes the code between Lock() and Unlock() at a time, preventing incorrect modification of shared data.