Qt-UI

Race Condition

Threads and Processes | | Threads and Mutexes

Supposed we have a situation where a single resource needs to be shared among multiple users of the resource, but the resource can only be used by one user at a time.

Simple example: Making Tom Kha Gai in a wok:

  1. Get wok from its place
  2. Put ingredients in wok
  3. Cook and stir
  4. Clean wok
  5. Put wok back at its place

If multiple users want to make Tom Kha Gai they need to synchronize their use of the shared resource wok by waiting until the other person is finished having returned the wok to its place:

bool wok_at_place = true;

void tom_kha_gai()
{
   while (!wok_at_place) ; // busy waiting

   wok_at_place = false;

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

   wok_at_place = true;
}

But what is the problem with the race condition then? It happens when claiming the wok!

Supposed, two persons/threads are waiting for the wok. The first one sees the wok at its place and wants to take it. But before it can do so by marking it as being no longer at its place its time slice runs out and the second person/thread is resumed. It also sees the wok at its place because the state has not yet been updated by chance and starts claiming it. Now we have two persons cooking with the same wok at the same time. Not good!

The problem that caused the race condition was that determining if the wok is free and claiming it could be interrupted. This needs to be an atomic non-interruptible operation for the process of cooking Tom Kha Gai to work out well and tasty.

How is that achieved? The operation of requesting and claiming the wok needs to be performed mutually exclusive for all persons/threads. For that purpose we use a so called mutex.

Note: I might seem that the chance of being interrupted at the wrong time is very small. Well, let’s have a closer look at the example. It turns out, that each person that has not gained access to the resource is busy waiting for it to be returned. Let’s call that the inactive person. If the wok is returned it gets claimed immediately, but the active person/thread will be probably busy preparing the next soup. Now we have the situation that the times slice for the active person is probably not used up, so it will be busy waiting for the wok and claim the wok immediately again. As a consequence, the inactive person will probably never get to see the wok at all if the active person is not cooperative. There is only the slight chance that program execution is interrupted in the very moment the active person is finished. But for that case, the chances are equally high that program execution is interrupted just a few steps later at the very moment of the race condition.

Threads and Processes | | Threads and Mutexes

Options: