Logo

Developer learning path

Go

Mutex in Go

Mutex

88

#description

A Mutex is a synchronization primitive used to control access to shared resources within concurrent programming. It stands for "mutual exclusion".

In Go, the sync package provides support for Mutexes through the sync.Mutex type. A Mutex has two main methods: Lock() and Unlock(). When a goroutine acquires a Lock on a Mutex, any other goroutines attempting to Lock the same Mutex will block until the first goroutine releases the Mutex using Unlock(). This assures that only one goroutine at a time will access the shared resource protected by the Mutex.

Mutexes are a useful tool to prevent race conditions, which can occur when multiple concurrent processes or threads access a shared resource without properly synchronizing access. Race conditions can lead to unexpected and unpredictable behaviors when two or more goroutines attempt to access the same resource at the same time, potentially overwriting or corrupting data.

Using Mutexes in Go is relatively straightforward. When a goroutine needs to access a shared resource protected by a Mutex, it should first call Lock() to acquire the Mutex. When it is finished using the resource, it should call Unlock() to release the Mutex so that other goroutines may access the resource.

Here's an example:

                    
package main

import (
	"fmt"
	"sync"
)

var counter int = 0
var mutex = &sync.Mutex{}

func main() {
	wg := &sync.WaitGroup{}
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go incrementCounter(wg)
	}
	wg.Wait()
	fmt.Println("Counter: ", counter)
}

func incrementCounter(wg *sync.WaitGroup) {
	mutex.Lock()
	counter += 1
	mutex.Unlock()
	wg.Done()
}
                  

In this example, a Mutex is used to synchronize access to a shared counter variable, which is incremented by 1 in each goroutine. Without the Mutex, the results would be unpredictable since all 100 goroutines could potentially attempt to access and modify counter simultaneously. By using a Mutex, we ensure that only one goroutine at a time can access the shared counter variable, preventing race conditions and ensuring the final result is predictable.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.