Mutex Introduction

  • MUTual EXclusion object
  • We can use a mutex to implement locking
  • A mutex has two states
    • "locked"
    • "unlocked"

Mutual Exclusion

  • Exclusion
    • The mutex is used to exclude threads from the critical section
  • Mutual
    • The threads agree to respect the mutex
  • Locking
    • If the mutex is unlocked, a thread can enter the critical section
    • If the mutex is locked, no thread can enter until it becomes unlocked
    • A thread locks the mutex when it enters the critical section
    • A thread unlocks the mutex when it leaves the critical section

Thread Synchronization with Mutex

  • Some threads A, B, C, ... wish to enter a critical section

    • Thread A locks the mutex
    • Thread A enters the critical section
    • Threads B, C... wait until they can lock the mutex
    • Thread A leaves the critical section
    • Thread A unlocks the mutex
    • One of threads B, C, ... can now lock the mutex and enter the critical section
  • The threads are synchronized

    • They cannot interleave when they execute in the critical section
    • There is no data race
  • Unlocking a mutex "publishes" any changes

    • Thread A modifies shared data
    • The new value is now available to other threads
    • It will be seen by the next thread which accesses the shared data

Acquire-Release Semantics

  • A thread locks a mutex

    • It "acquires" exclusive access to the critical section
  • The thread unlocks the mutex

    • It "releases" exclusive access to the critical section
    • It also "releases" the result of any modifications
    • The next thread that locks the mutex will acquire these results
  • These acquire-release semantics impose ordering on the threads

    • There is no data race
    • The shared data is always in a consistent state