How to protect critical sections of code with a mutex in Golang?

To protect critical sections of code with a mutex in Golang, you can follow these steps:

  1. Import the sync package that contains the Mutex type.
import "sync"
  1. Define a variable of type Mutex to create a mutual exclusion lock.
var mutex = &sync.Mutex{}
  1. Wrap the critical section of code with the 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.