RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Dispose of Proprietary Threading APIs and Adopt the New C++ Threading Facilities

Prior to C++0x, multithreaded C++ applications relied on platform-specific features that were neither portable nor easy to grasp. C++0x fixes this omission with a new multithreading library. Learn how to use this new library to write portable and clean multithreaded C++ code.


ntil not long ago, a standardized multithreading API for C++ was a pipe dream. Almost every operating system, compiler, and framework rolled their own threading libraries. These proprietary libraries were complex, non-portable, and didn't support object-oriented idioms such as function objects. In the following sections, you'll learn how to create threads and mutexes in the C++0x fashion.

As multicore processors become predominant, you want to write multithreaded C++ code that's both efficient and portable.

Migrate to the new C++0x threading libraries.

Hang By a Thread
At the heart of the new C++0x threading library lies std::thread, which provides mechanisms for creating a new thread of execution, waiting for a thread to complete (this is know as a joining with a thread), and querying the state of a thread. You launch a new thread by instantiating a std::threadobject initialized with a function:

#include <thread>

void spellcheck();
std::thread thr(spellcheck);

The preceding code invokes spellcheck() when it creates thr. When spellcheck() returns the thread is finished. std::thread can take any callable entity as its argument, not just a plain old function. The following code passes a function objectas an argument:

class spellcheck
 void operator()();
spellcheck sp
std::thread thr(sp);

thr actually gets a copy of sp. If you don't want to create copies, wrap the arguments in a reference wrapper:

spellcheck sp;
std::thread thr(std::ref(sp));

This is all well and good, but how do you pass arguments to the thread function itself? In traditional threading frameworks, you'd typically pack parameters in an opaque pointer. Fortunately, those days are gone. std::threaduses another new C++ feature called variadic templates, which allows you to pass any number of arguments to the thread function:

spellcheck(CDocument *p, string slocale, bool igncase);

std::thread thr(spellcheck, pd, "en_UK", true);

All the examples above launch a new thread upon initialization. In some cases you want to create an "empty" thread—one that does not represent a thread of execution. Although copying threads isn't allowed (and doesn't make any sense either), you can movean active thread into an empty thread like this:

std::thread thr(spellcheck,pd,"en_UK",true);
std::thread thr2;  

Or simply call swap():


Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date