Mutex in Go
Go: Mutex
A mutex (short for "mutual exclusion") is a synchronization primitive that allows you to protect shared resources from concurrent access by multiple goroutines. A mutex has two states: locked and unlocked. When a mutex is locked, any goroutine that attempts to lock it will block until the mutex is unlocked. When a mutex is unlocked, the next goroutine that attempts to lock it will succeed and continue running.
How to use a mutex in Go
Here's an example of how you might use a mutex in Go to protect access to a shared variable:
package main
import (
"fmt"
"sync"
)
var (
count int
mutex sync.Mutex
)
func increment() {
mutex.Lock()
count++
mutex.Unlock()
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
increment()
}()
}
wg.Wait()
fmt.Println("Final count:", count)
}
- In above example, we have a count variable that is shared among multiple goroutines. We use a mutex to protect access to the count variable, so that only one goroutine can access it at a time.
- The increment function acquires the mutex by calling mutex.Lock(), increments the count variable, and then releases the mutex by calling mutex.Unlock().
- The main function creates 1000 goroutines, each of which calls increment, and then waits for all of them to finish before printing the final value of count.
Using a mutex in this way ensures that the count variable is incremented atomically, meaning that there are no race conditions or other synchronization issues that could cause the final value of count to be incorrect.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go