Qt-UI

Threads and Mutexes

Race Condition | | QThread and QMutex

In order to cook Tom Kha Gai concurrently, we have to solve two problems:

1) Use a mutually exclusive operation to claim the wok. 2) Establish fair sharing practices.

Both problems are solved with a Mutex. A mutex can be locked and unlocked. If one thread has locked a mutex other threads that want to do the same are put to sleep to be woken up until the lock is released.

mutex wok;

void tom_kha_gai()
{
   wok.lock();

   put_ingredients();
   cook_and_stir();
   clean_wok();

   wok.unlock();
}

Has that solved the problem with the race condition then?

Yes, because locking and unlocking a mutex is an atomic operation! If there are other persons that want to get the wok, they are put in waiting condition. Persons in waiting condition are invoked when other persons return the lock on the same mutex, so that the latter do not get to claim the wok again.

Race Condition | | QThread and QMutex

Options: