To create and use a mutex in Go for managing concurrent access to data, you can follow these steps:
sync
package, which provides synchronization primitives like the Mutex
.import "sync"
sync.Mutex
to represent the mutex.var mutex sync.Mutex
Lock()
method of the mutex variable. This will ensure exclusive access to the shared data.mutex.Lock()
// Perform operations on the shared data
sharedData := 10
sharedData++
Unlock()
method of the mutex variable. This will allow other goroutines to acquire the lock and access the shared data.mutex.Unlock()
Here's a complete example that demonstrates the usage of a mutex for managing concurrent access to a shared counter:
package main
import (
"fmt"
"sync"
"time"
)
var counter int
var wg sync.WaitGroup
var mutex sync.Mutex
func main() {
wg.Add(2)
go increment()
go increment()
wg.Wait()
fmt.Println("Final Counter:", counter)
}
func increment() {
for i := 0; i < 10; i++ {
mutex.Lock()
counter++
time.Sleep(time.Millisecond * 100)
fmt.Println("Counter value:", counter)
mutex.Unlock()
}
wg.Done()
}
In this example, two goroutines increment the counter
variable concurrently. The mutex.Lock()
and mutex.Unlock()
calls ensure that only one goroutine can access the shared counter
variable at a time, thus preventing race conditions.