skip to content
Alvin Lucillo

Atomic operations with Go's sync.Mutex

/ 1 min read

💻 Tech

In tech journal last April 14, 2024, sync/atomic package was used to ensure atomicity when performing operations with goroutines involved. The same can be achieved by using sync.Mutex.

func main() {
	var mu sync.Mutex // common practice to put mutex definition at the top of the variable it is guarding
	count := 0

	const x = 10
	var wg sync.WaitGroup
	wg.Add(n)
	for i := 0; i < x; i++ {
		go func() {
			defer wg.Done()
			for j := 0; j < 10_000; j++ {
				mu.Lock()
				count++ // non atomic operation
				mu.Unlock()
			}

		}()
	}

	wg.Wait()
	fmt.Println(count) // prints 100000
}