How to create and use a mutex in Go for managing concurrent access to data?

To create and use a mutex in Go for managing concurrent access to data, you can follow these steps:

  1. Import the sync package, which provides synchronization primitives like the Mutex.
import "sync"
  1. Declare a variable of type sync.Mutex to represent the mutex.
var mutex sync.Mutex
  1. Lock the mutex before accessing the shared data by calling the Lock() method of the mutex variable. This will ensure exclusive access to the shared data.
mutex.Lock()
  1. Perform the necessary operations on the shared data.
// Perform operations on the shared data sharedData := 10 sharedData++
  1. Unlock the mutex after accessing the shared data by calling the 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.