To protect critical sections of code with a mutex in Golang, you can follow these steps:
sync
package that contains the Mutex
type.import "sync"
Mutex
to create a mutual exclusion lock.var mutex = &sync.Mutex{}
Lock
and Unlock
methods of the mutex.mutex.Lock()
// Critical section of code
mutex.Unlock()
Here's an example to demonstrate the usage of mutex in Golang:
package main
import (
"fmt"
"sync"
)
var (
counter = 0
mutex = &sync.Mutex{}
)
func increment() {
mutex.Lock()
counter++
mutex.Unlock()
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
increment()
wg.Done()
}()
}
wg.Wait()
fmt.Println("Counter:", counter)
}
In this example, the counter
variable is shared among multiple goroutines, and the increment
function is the critical section that modifies the counter. By using a mutex, we ensure that only one goroutine can access the critical section at a time, preventing concurrent modification and potential data races.