#best-practice #development #golang #pattern

Mutexes let you synchronize data access by explicit locking, without channels.

Sometimes it's more convenient to synchronize data access by explicit locking instead of using channels. The Go standard library offers a mutual exclusion lock, sync.Mutex, for this purpose.

For this type of locking to be safe, it's crucial that all accesses to the shared data, both reads and writes, are performed only when a goroutine holds the lock. One mistake by a single goroutine is enough to introduce a data race and break the program.

Because of this you should consider designing a custom data structure with a clean API and make sure that all the synchronization is done internally.

In this example we build a safe and easy-to-use concurrent data structure, AtomicInt, that stores a single integer. Any number of goroutines can safely access this number through the Add and Value methods.

 1// AtomicInt is a concurrent data structure that holds an int.
 2// Its zero value is 0.
 3type AtomicInt struct {
 4    mu sync.Mutex // A lock than can be held by one goroutine at a time.
 5    n  int
 6}
 7
 8// Add adds n to the AtomicInt as a single atomic operation.
 9func (a *AtomicInt) Add(n int) {
10    a.mu.Lock() // Wait for the lock to be free and then take it.
11    a.n += n
12    a.mu.Unlock() // Release the lock.
13}
14
15// Value returns the value of a.
16func (a *AtomicInt) Value() int {
17    a.mu.Lock()
18    n := a.n
19    a.mu.Unlock()
20    return n
21}
22
23func main() {
24    wait := make(chan struct{})
25    var n AtomicInt
26    go func() {
27        n.Add(1) // one access
28        close(wait)
29    }()
30    n.Add(1) // another concurrent access
31    <-wait
32    fmt.Println(n.Value()) // 2
33}