How to create a simple mutex lock in Golang using sync.Mutex?

To create a simple mutex lock in Golang using sync.Mutex, you can follow these steps:

Step 1: Import the sync package.

import "sync"

Step 2: Create a variable of type sync.Mutex to use as the mutex lock.

var mutex = &sync.Mutex{}

Step 3: Use the mutex.Lock() and mutex.Unlock() methods to lock and unlock the critical section of code.

// Lock the critical section mutex.Lock() defer mutex.Unlock() // Your code here // Unlock the critical section

By calling mutex.Lock(), you acquire the lock and prevent other goroutines from executing the critical section. Once your code is finished with the critical section, you can release the lock by calling mutex.Unlock(). The defer statement ensures that the lock will be released even if an error occurs or a panic is raised within the critical section.

Here's an example that demonstrates the usage of sync.Mutex:

package main import ( "fmt" "sync" ) var counter = 0 var mutex = &sync.Mutex{} func increment() { // Lock the critical section mutex.Lock() defer mutex.Unlock() counter++ fmt.Println(counter) } func main() { for i := 0; i < 10; i++ { go increment() } // Wait for all goroutines to complete wg := &sync.WaitGroup{} wg.Add(1) wg.Wait() }

In the example above, the increment function is called concurrently by multiple goroutines. The mutex.Lock() and mutex.Unlock() methods ensure that only one goroutine can increment the counter variable at a time, preventing race conditions.