Thread Safety - Examples

Examples

In the following piece of C code, the function is thread-safe, but not reentrant:

#include int increment_counter { static int counter = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mutex); // only allow one thread to increment at a time ++counter; // store value before any other threads increment it further int result = counter; pthread_mutex_unlock(&mutex); return result; }

In the above, increment_counter can be called by different threads without any problem since a mutex is used to synchronize all access to the shared counter variable. But if the function is used in a reentrant interrupt handler and a second interrupt arises inside the function, the second routine will hang forever. As interrupt servicing can disable other interrupts, the whole system could suffer.

The same function can be implemented to be both thread-safe and reentrant using the lock-free atomics in C++11:

#include int increment_counter { static std::atomic counter(0); // increment is guaranteed to be done atomically int result = ++counter; return result; }

Read more about this topic:  Thread Safety

Famous quotes containing the word examples:

    No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.
    André Breton (1896–1966)

    Histories are more full of examples of the fidelity of dogs than of friends.
    Alexander Pope (1688–1744)

    In the examples that I here bring in of what I have [read], heard, done or said, I have refrained from daring to alter even the smallest and most indifferent circumstances. My conscience falsifies not an iota; for my knowledge I cannot answer.
    Michel de Montaigne (1533–1592)