Multithreaded C++: Part 2: Boost Threads
If pthreads represent the assembly language of multithreading programming, then boost::threads represent the C of multithreaded programming.
Boost threads introduce some handy code saving features for the creation of threads, which is nice, but not as important as the RAII techniques they put to use for mutex management. In this case an example is worth a thousand words. Here is the same code we wrote in for pthreads rewritten for boost::threads:
// Create the thread and start work
m_thread = boost::shared_ptr<boost::thread>(new boost::thread(boost::bind(&threaded_class::do_work, this)));
void stop() // Note 1
m_stoprequested = true;
int get_fibonacci_value(int which)
boost::mutex::scoped_lock l(m_mutex); //Note 2
volatile bool m_stoprequested;
int fibonacci_number(int num)
return fib(num-2) + fib(num-1);
// Compute and save fibonacci numbers as fast as possible
int iteration = 0;
int value = fibonacci_number(iteration);
From the last pthreads example to this example our entire implementation, including comments and white space, decreased from 78 lines of code to 64. In this simple case, that was an 18% savings. Smaller, easier to read code is less error prone and easier to maintain (and therefore cheaper to write and maintain). We'll see in future articles that we can keep going with this, making the code even more succinct.
Notes regarding this version:
- Note 1
- In this version we still have the problem we had in the pthreads version. If we forget to call "stop" on this object we are going to at least leak thread resources and probably cause a crash.
- Note 2
boost::mutex::scoped_lockclass provides a handy RAII way of managing mutex locks. In our pthread only version we were very much at risk of forgetting to unlock a mutex we had locked, causing a difficult to debug deadlock.
In this case, the length of the mutex is governed by the lifetime of the scoped_lock object. Because the scoped_lock will be destroyed as soon as it goes out of scope we know we are guaranteed to never forget to unlock the mutex.