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:
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:
thr actually gets a copy of sp. If you don't want to create copies, wrap the arguments in a reference wrapper:
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:
Or simply call swap():