concurrency

Atomic Operations

Simple low-level operations guaranteed to either fully complete, or not at all. No risk of partially completing.

In go, use import "sync/atomic" .

Mutexes

Use when atomic operations are not possible.

  • Need to operate on complex data types

  • Need to operate on multiple objects

How Mutexes Work

The lock is like a baton in a relay race. Only one thread can hold the lock for each mutex at once.

The mutex is not attached to a piece of memory at all. It's a separate object used for coordinating read/write to an object.

Only one thread can hold the lock for a given mutex at a time.

If a thread locks a mutex, all other threads will be blocked from acquiring that mutex until the first one unlocks.

Read/Write Mutexes

Read/write mutexes allow multiple threads to hold a read lock at the same time, but only one to hold a write lock at a time.

Last updated