Mutexes in Go
Mutexes are a synchronization mechanism provided by the sync package. A Mutex can be used to provide exclusive access to a shared resource.
Here's an example of using a Mutex:
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
counter++
mu.Unlock()
}
for i := 0; i < 10; i++ {
go increment()
}
time.Sleep(time.Second)
fmt.Println(counter) // prints 10
In this example, we create a Mutex and a shared counter variable. We then create 10 goroutines that call the increment function, which increments the counter using the Lock and Unlock methods of the Mutex.
The Mutex ensures that only one goroutine can access the shared resource at a time, preventing data races and ensuring consistency.
No comments:
Post a Comment