Thread Local Data
keyword can be used with any object declaration at namespace scope at local scope, and specifies that such a variable is thread local. Each thread thus has its own copy of that variable, and that copy exists for the entire duration of that thread. It is essentially a per-thread static variable, so each thread's copy of a variable declared at local scope is initialized the first time that particular thread passes through the declaration, and they retain their values until that thread exits:
std::string foo(std::string const& s2)
thread_local std::string s="hello";
In this function, each thread's copy of s
starts life with the contents "hello." Every time the function is called, the supplied string is appended to that thread's copy of s
. As you can see from this example, this even works with class types that have constructors and destructors (such as std::string
), which is an improvement over the pre-C++0x compiler extensions.
Thread-local storage isn't the only change to the concurrency support in the core language: There's also a brand new multi-threading aware memory model, with support for atomic operations.
The New Memory Model and Atomic Operations
Sticking to using locks and condition variables to protect your data, you won't need to worry about the memory model. The memory model guarantees to protect your data from race conditionsif you use locks correctly. You'll get undefined behavior if you don't.
If you're working at a really low-level and providing high-performance library facilities, then it's important to know the detailswhich are too complicated to go into here. For now, it's enough to know that C++0x has a set of atomic types corresponding to the built-in integer types and void pointersand a template std::atomic<>which can be used to create an atomic version of a simple user-defined type. You can look up the relevant documentation for the details.
That's All, Folks!
And that’s your whistle-stop tour of the new C++0x threading facilities, which has barely scratched the surface. There's much more to the library, with features such as thread IDs and asynchronous future values.