Tutorial : Synchronization Primitives

Previous : Task Based Programming Top : Tutorial  

Synchronization Primitives

The Intel® Threading Building Blocks (Intel® TBB) library provides synchronization primitives for mutual exclusion and to perform atomic operations.  Mutual exclusion controls how many threads can simultaneously run a region of code. In Intel TBB, mutual exclusion is implemented by mutexes and locks. A mutex is an object on which a thread can acquire a lock. Only one thread at a time can have a lock on a mutex; other threads have to wait their turn.

You can avoid mutual exclusion using atomic operations. When a thread performs an atomic operation, the other threads see it as happening instantaneously. The advantage of atomic operations is that they are relatively quick compared to locks, and do not suffer from deadlock and convoying. The disadvantage is that they only do a limited set of operations, and often these are not enough to synthesize more complicated operations efficiently.

The example below shows the use of class spin_mutex to control access to a free list.  The constructor for scoped_lock waits until there are no other locks on FreeListMutex. The destructor releases the lock. The braces inside routine AllocateNode may look unusual. Their role is to keep the lifetime of the lock as short as possible, so that other waiting threads can get their chance as soon as possible.

Node* FreeList;
typedef tbb::spin_mutex FreeListMutexType;
FreeListMutexType FreeListMutex;

Node* AllocateNode() {
    Node* n;
        FreeListMutexType::scoped_lock lock(FreeListMutex);
        n = FreeList;
        if( n )
            FreeList = n->next;
    if( !n )
        n = new Node();
    return n;

void FreeNode( Node* n ) {
    FreeListMutexType::scoped_lock lock(FreeListMutex);
    n->next = FreeList;
    FreeList = n;

There are a number of resources available to learn more about the task scheduling features in the Intel® Threading Building Blocks library.


Previous : Task Based Programming Top : Tutorial