A mutex
is a synchronization mechanism that controls access to a shared resource in a concurrent environment. In Go, the sync
package provides a Mutex
type that can be used to implement mutual exclusion, ensuring that only one Goroutine can access a shared resource at any given time.
Here’s an example of using a Mutex
in Go:
package main
import (
"fmt"
"sync"
"time"
)
var counter int
var mutex sync.Mutex
func incrementCounter(wg *sync.WaitGroup) {
defer wg.Done()
for i := 0; i < 1000; i++ {
mutex.Lock()
counter++
mutex.Unlock()
time.Sleep(time.Millisecond)
}
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go incrementCounter(&wg)
}
wg.Wait()
fmt.Println("Final Counter Value:", counter)
}
In this example, a global variable counter
is declared and a Mutex
named mutex
is used to control access to it. A Goroutine incrementCounter
increments the value of the counter 1000 times. The Goroutine acquires the lock using the mutex.Lock
method before accessing the counter and releases the lock using the mutex.Unlock
method after the increment operation is complete. The use of a Mutex
ensures that only one Goroutine can access the counter at any given time, preventing race conditions and ensuring the integrity of the shared resource.
Leave a Reply