Implement a thread-safe counter in Go by wrapping an integer with a sync.Mutex to lock access during read and write operations.
Use a sync.Mutex to guard access to the counter variable, ensuring only one goroutine modifies it at a time.
package main
import (
"sync"
)
type Counter struct {
mu sync.Mutex
val int
}
func (c *Counter) Increment() {
c.mu.Lock()
defer c.mu.Unlock()
c.val++
}
func (c *Counter) Value() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.val
}
A thread-safe counter prevents multiple parts of your program from updating a number at the exact same moment, which causes data to be lost or corrupted. Think of it like a single checkout line at a store; the mutex ensures only one person can pay at a time, keeping the total accurate. You use this pattern whenever multiple goroutines need to read or write to the same variable.