Using sync package to implement Mutex in Go

Simple example demonstrating how to use a mutex

Anonymous

In Go, you can implement a mutex (short for mutual exclusion) using the sync package, specifically the sync.Mutex type. Here's a simple example demonstrating how to use a mutex to protect a critical section of code:

package main

import (
	"fmt"
	"sync"
	"time"
)

// Shared resource
var counter int

// Mutex to synchronize access to the shared resource
var mutex sync.Mutex

// Function to increment the counter safely using a mutex
func incrementCounter() {
	// Lock the mutex to prevent concurrent access to the shared resource
	mutex.Lock()
	defer mutex.Unlock() // Ensure the mutex is unlocked when the function exits

	// Critical section: Manipulate the shared resource
	counter++
	fmt.Println("Counter incremented to:", counter)
}

func main() {
	// Number of goroutines (simulating concurrent access)
	numGoroutines := 5

	// Create multiple goroutines to concurrently increment the counter
	for i := 0; i < numGoroutines; i++ {
		go incrementCounter()
	}

	// Sleep to allow goroutines to execute
	time.Sleep(time.Second)

	// Output the final value of the counter
	fmt.Println("Final counter value:", counter)
}
  1. We define a shared resource counter that multiple goroutines will concurrently access.

  2. We create a mutex named mutex using sync.Mutex.

  3. The incrementCounter function is defined to increment the counter safely using the mutex. It locks the mutex before accessing the critical section and defers unlocking the mutex to ensure it's always released.

  4. In the main function, we create multiple goroutines to concurrently call incrementCounter.

  5. After a brief delay to allow the goroutines to execute, we output the final value of the counter.

By using the mutex, we ensure that only one goroutine can access the critical section (incrementing the counter) at any given time, preventing data races and ensuring the correctness of the program.

Techgoda

We are a community of developers who are passionate about technology and programming.

Check out Techgoda code