Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

On One Condition

Mutexes are good for protecting data structures, but they’re not always ideal for more general synchronization purposes. In a lot of situations, you’ll want a more event-driven model; a thread should wait until a condition is met and then run.

The condition variable was created for this situation. A condition variable is conceptually similar to a signal; it’s a way of sending one bit of information from one thread to another. Unlike a signal, however, with a condition variable a process must be waiting explicitly for the condition variable to receive it.

Consider two threads, one of which must run whenever the other one is in a certain state. This goal could be achieved by having one wait on a condition variable and the other signal it when it was in the correct state. Unfortunately, with parallel programming you’re forced to consider the fact that your thread can be in any state when you signal it. If the thread is processing rather than waiting, it will miss the signal and continue to wait.

Fortunately, the designers of the pthread condition variables thought of this possibility. When you wait on a condition variable, you actually perform three actions:

  1. Release a mutex.
  2. Wait on the condition variable.
  3. Reacquire the mutex.

The first two of these actions happen atomically. Typically, when you signal a condition variable you’ll first acquire the corresponding mutex. Then, when the signaled thread wakes up, it will block between stages 2 and 3 until you release the mutex, at which point it will continue.

To avoid missing notifications, a thread should first acquire the mutex and then test the condition. If the condition is not met, the thread should wait on the condition variable, releasing the mutex.

Once a thread is awakened, a further complication ensues. There are two ways of waking a process waiting on a condition variable: signaling and broadcasting. If a thread broadcasts, it will wake up all processes sleeping on the condition variable. If it signals, it will awaken at least one. Unfortunately, the specification is somewhat vague on how many threads are awakened by signaling a condition variable. On some implementations it’s always one, on some it’s all of them, and on some it’s one per physical processor. Unless you can be absolutely certain that yours is the only thread waiting on a condition variable, your first action on awakening—even before releasing the mutex—should be to check whether the condition has already been handled.

The example in Listing 3 contains four threads engaged in a game of three-on-one ping-pong. One thread "pings" and then another thread replies with "pong."

Listing 3 ping-pong.c.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
#include <unistd.h>

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;

int flag=0;

void * ping(void* spare)
{
    while(1)
    {
       sleep(2);
       pthread_mutex_lock(&lock);
       printf("Ping!\n");
       flag += 1;
       pthread_cond_signal(&condition);
       pthread_mutex_unlock(&lock);
    }
}
void * pong(void* threadID)
{
    while(1)
    {
       pthread_mutex_lock(&lock);
       if(flag < 1)
       {
           pthread_cond_wait(&condition, &lock);
       }
       if(flag > 0)
       {
           printf("Pong! (%d)\n",(int)threadID);
           flag--;
       }
       pthread_mutex_unlock(&lock);
    }
}

int main(void)
{
    pthread_t thread1, thread2;
    pthread_create(&thread1, NULL, pong, (void*)1);
    pthread_create(&thread1, NULL, pong, (void*)2);
    pthread_create(&thread1, NULL, pong, (void*)3);
    pthread_create(&thread2, NULL, ping, NULL);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    return 0;
}

Before the ping thread signals the condition variable, it sets a global variable to 1. When a pong thread awakes, it first checks whether this is still the case. If it is, it prints Pong! to the screen, and then loops.

Note that the pong threads also check the status of the flag after acquiring the mutex, and don’t wait on the condition variable if it’s already greater than 0. This technique prevents the pong threads from missing any signals. In this example, missed signals are not a problem, because the condition variable is only signaled every two seconds and the pong thread takes a fraction of a second to process it. If you want to see missed signals become a reality, add a sleep statement to the end of the pong thread’s run loop (about 10 seconds should be enough). Now all of the pong threads will be sleeping when the condition variable is signaled, and will miss it.

This pattern typically is used when you have a series of jobs that take a long time to process. A web server, for example, might use this pattern for generating dynamic content. Every time a request was received, the program would add the request to a queue and signal a group of worker threads. One would then wake up and process the request. This usage provides a simple way of distributing tasks among threads.

  • + Share This
  • 🔖 Save To Your Account