O'Reilly logo

Intel Threading Building Blocks by James Reinders

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Mutexes

Mutexes provide mutual exclusion of tasks from sections of code.

In general, strive for designs that minimize the use of explicit locking, because it can lead to serial bottlenecks. If explicit locking is necessary, try to spread it out so that multiple tasks usually do not contend to lock the same mutex.

Mutex Concept

The mutexes and locks here have simple interfaces that are designed for high performance. The interfaces enforce the scoped locking pattern, which is widely used in C++ libraries because:

  • It does not require the programmer to remember to release the lock.

  • It releases the lock if an exception is thrown out of the mutual exclusion region protected by the lock.

There are two parts to the pattern: a mutex and a lock. The constructor of the lock object acquires the lock, and the destructor of the lock object releases the lock. Here’s an example:

	{
	    // Construction of myLock acquires lock on myMutex
	    M::scoped_lock myLock( myMutex );
	    ... actions to be performed while holding the lock ...
	    // Destruction of myLock releases lock on myMutex
	}

If the actions throw an exception, the lock is automatically released as the block is exited.

Table 7-2 summarizes the classes that model the Mutex Concept.

Table 7-2. Mutex Concept

Pseudosignature

Semantics

M ()

Construct unlocked mutex.

~M ()

Destroy unlocked mutex.

M ::scoped_lock( )

Construct lock without acquiring mutex.

M ::scoped_lock(M&)

Construct lock and acquire lock on mutex.

M ::~scoped_lock( )

Release lock ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required