Mutex
What is it
- mutual exclusion
- a synchronization primitive used in concurrent programming to ensure that only one thread can access a shared resource at a time
How it works
- Locking:
- a thread that needs to access a sahred resource acquires the mutex lock
- if the mutex is already locked by another thread, the requesting thread is blocked until the lock is released
- Critical Section
- once the lock is acquired, the thread enters a critical section, where it accesses and modifies the shared resource
- Unlocking
- After the thread finishes with the shared resource, it releases the mutex lock
Key Points:
-
Atomic: mutexes ensures that operations on shared resources are atomic, meaning they are indivisible and cannot be interupted by other threads
-
Deadlocks: Improper use of mutexes can lead to deadlocks, where two or more threads are waiting for each other to release locks, resulting in a stalemate
-
Starvation: In some cases a thread may be repeatedly denied access to a shared resource, even if it's available, due to other threads continuously acquiring and releasing the lock.
Example:
package main
import (
"fmt"
"sync"
)
var counter int
var mu sync.Mutex
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
func main() {
for i:=0; i<1000; i++ {
go increment()
}
// wait for al lgoroutines to finish
fmt.Println("Final counter value: ", counter)
}