Condition Variable and Measure the Speed of Context Switching

The pthread tutorial gives a concise but clear description about condition variable:

  • While mutexes implement synchronization by controlling thread access to data, condition variables allow threads to synchronize based upon the actual value of data.
  • A condition variable is always used in conjunction with a mutex lock.

And a representative sequence for using condition variables is shown below.

Two important points from above illustration:

  1. pthread_cond_wait unlocks the mutex so  another thread can have the chance to signal the condition variable.
  2. When signaled, pthread_cond_wait locks the mutex. (If the mutex is locked by another thread, pthread_cond_wait has to wait for the mutex before returning.)

To better understand condition variable, let us take a look at the answer to a Google interview question: how to measure the speed of context switch.  The answer was given in:

Ah, UNIX stuff. Essentially you would create a function to alternate between persistant thread states, set lock and start/wakeup/sleep conditions plus a counter.

uint32_t COUNTER;
pthread_mutex_t LOCK;
pthread_mutex_t START;
pthread_cond_t CONDITION;
void * threads (void * unused) {
    if (COUNTER > 0) {
    for (;;) {
        pthread_cond_wait(&CONDITION, &LOCK);

Next we create persistant threads t1 and t2 which are unlocked (awoken), and we roughly sleep one second to let them do their firing. (rough approximate of one second, granularity is different among platforms/clocks)

    COUNTER = 0;
    pthread_create(&t1, NULL, threads, NULL);
    pthread_create(&t2, NULL, threads, NULL);
    myTime = tTimer();
    // Lock both simulaneous threads
    //Normalize the result in second precision
    myTime = tTimer() - myTime / 1000;
Here follows my explanation on how above code works:
At first, only one persistent thread (say t1) can lock LOCK, so t2 waits. t1 then fulfills the condition (COUNTER++) but waits.  Since the main thread sleeps once it lets persistent threads go, so only the other persistent thread (t2) can be waken up (one switching). t2 signals CONDITION, but t1 cannot wait right now because t2 holds LOCK, and t1’s wait invocation have to wait until t2 unlocks LOCK.  Therefore, t2 goes on increase COUNTER and waits.  Since the wait invocation unlocks LOCK, so t1 now wakes up and signals CONDITION.  Similarly, t2 cannot wake up right now but has to wait until t1 increase COUNTER and actively waits again.

Using C++ mutable Keyword

The keyword mutable is used to allow a particular data member of const object to be modified.

In this interesting post, two examples are given:

class Employee {
    Employee(const std::string & name) 
        : _name(name), _access_count(0) { }
    void set_name(const std::string & name) {
        _name = name;
    std::string get_name() const {
        return _name;
    int get_access_count() const { return _access_count; }

    std::string _name;
    mutable int _access_count;

As a more complex example, you might want to cache the results of an expensive operation:

class MathObject {
    MathObject() : pi_cached(false) { }
    double pi() const {
        if( ! pi_cached ) {
            /* This is an insanely slow way to calculate pi. */
            pi = 4;
            for(long step = 3; step < 1000000000; step += 4) {
                pi += ((-4.0/(double)step) + (4.0/((double)step+2)));
            pi_cached = true;
        return pi;
    mutable bool pi_cached;
    mutable double pi;

Another example is the C++ encapsulation of a blocking queue, which is the intermediate between producers and consumers:

class BlockingQueue {
    bool IsEmpty() const
        MutexLocker locker(m_mutex);
        return m_queue.empty();
    size_t m_max_elements;
    std::deque<T> m_queue;

    mutable Mutex m_mutex;
    ConditionVariable m_cond_not_empty;
    ConditionVariable m_cond_not_full;

POSIX Thread and Semaphore on Darwin and Cygwin

Darwin (here I mean Mac OS X up to 10.6.5) supports pthread and semaphore.  However, it is notable that only named semaphores (sem_open and sem_close) are supported, unnamed semaphores (sem_init and sem_destroy) are not.

Cygwin supports full pthread and semaphore.

To make your program compatible with both platforms, use the following macros (

#include <unistd.h>

#if ((_POSIX_SEMAPHORES - 200112L) >= 0)
/* This platform fully supports POSIX semaphores */
#if defined(__APPLE__)
/* This platform can support POSIX named semaphores, but not unnamed semaphores */
/* this platform requires that I Google code for P/V semaphores and include it here */

Also, you need

#include <pthread.h>  // for POSIX thread mutex and condition variables
#include <semaphore.h>  // for POSIX semaphore

On both platforms, you can use g++ -lpthread to build programs using POSIX thread and semaphore.