CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Race conditions

Mutexes can be used to prevent race conditions. Consider this example of a race condition involving two threads attempting to add funds to a bank account:

Thread 1 Thread 2 Balance
Read balance: $1000 $1000
Read balance: $1000 $1000
Deposit $200 $1000
Deposit $200 $1000
Update balance $1000+$200 $1200
Update balance $1000+$200 $1200

In the above example, a mutex variable should be used to lock the balance (variable) while a thread is using this shared resource. Threads owning a mutex typically update global variable(s). When used correctly, the final result (value) is the same as would be observed if all updates were made by a single-threaded program.

The variables being updated belong to a critical section.

A typical sequence when using a mutex is as follows:

  • create and initialize a single mutex variable (shared by all threads),
  • several threads attempt to lock the mutex,
  • only one thread succeeds and that thread owns the mutex,
  • the owner thread performs some actions (such as updating a variable),
  • the owner unlocks the mutex,
  • another thread acquires the mutex and repeats the sequence, and
  • finally, the mutex is destroyed.

 


CITS2002 Systems Programming, Lecture 21, p2, 10th October 2023.