QamoosTech
Programming FundamentalsRuntime and memoryIntermediate

Mutex

PronunciationMYOO-teks

Definition

A mutex (mutual exclusion lock) lets only one thread at a time enter a critical section, the code that touches shared data, so threads can't corrupt each other's work.

Where you hear it

In multithreaded code, Python's threading.Lock, Go's sync.Mutex and database locking discussions.

Examples

  • Take the mutex before updating the shared counter.
  • Hold the lock for as short a time as possible.
  • The mutex stops two goroutines from updating the balance at the same time.

Common mistake

Forgetting to release the lock on an error path, or taking two locks in different orders. Both lead to deadlock.

Don't confuse with

A semaphore, which lets up to N threads in. A mutex is the special case where N is 1.

Say it at work

  • In a meeting or chatWrap this in a lock.
  • In an email or ticketUse with lock: so it is always released.