Skip to content

Go Atomic Operations vs Mutex

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Go Atomic Operations vs Mutex. We cover key concepts, practical examples, and best practices.

Atomic operations -- Use sync/atomic for lock-free concurrent access to integers, pointers, and booleans.

The Problem

sync.Mutex is heavy for simple integer operations. Atomic operations use CPU-level instructions for fast concurrent access.

Wrong

var counter int64
var mu sync.Mutex
mu.Lock()
counter++
mu.Unlock()

Output:

// Heavyweight for a simple increment
var counter int64
atomic.AddInt64(&counter, 1)
val := atomic.LoadInt64(&counter)

Output:

// Lock-free, CPU-level atomic increment

Prevention

  • Use atomic.Add* for counters
  • Use atomic.Load/Store for reading/writing
  • Use atomic.CompareAndSwap for conditional updates
  • Use atomic.Value for lock-free reads of interface{}
  • atomic is faster than mutex for simple operations

Common Mistakes with sync atomic

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What operations does atomic support?**

Add, Load, Store, Swap, CompareAndSwap (CAS).

Is atomic always faster?

Yes for simple operations. For complex critical sections, mutex is safer.

Can I use atomic for structs?

Use atomic.Value for lock-free reads/writes of structs (must be same type).


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro