Tuesday, January 13, 2009

C++0x Atomics and Concurrency Woes

If you've been through Java programming before, you'd know that one of the nice features would be the clear semantics for concurrency of the volatile keyword. If you wanted to say that a variable may change at any given time but be assured that changes to it would be atomic, you'd name it volatile. Not only that, if you wanted to make sure a method was executed atomically within the virtual machine, you'd mark it synchronized.

Until recently C++ lacks a volatile keyword that makes variables behave like atomic variables. The C++ volatile keyword is a directive to the compiler that says "hey, you can't assume anything about the storage/location of this variable -- so don't try and deduce and optimize away changes to this one". Herb Sutter has recently posted a summary of the explanation to the C++0x standard atomic template in his latest installment titled aptly "volatile vs. volatile".

If you look at illustrated table comparison between the semantics of Java/.NET's volatile keyword and C++'s volatile keyword it would be easy to see why people (like me included) are usually confused with what "volatile" is really about. Thankfully, C++0x has the atomic template to give us C++ developers the capability to use the same volatile semantics protecting types from unsynchronized access. Not only does this allow people to write essentially lock-free (in the normal sense using considerably heavy-weight mutexes) code and get the performance benefits of being really close to the metal.

Much is to be said about the upcoming C++0x implementation and what's really exciting for me are the concurrency-specific changes to be made part of the language and the standardization of libraries pertaining to concurrency -- threading, futures, among many other things. Right now it's a waiting game to find out who among the many vendors out there will be able to come up with reasonably compliant C++0x compilers first, and I for one am going to be trying out the new features of GCC 4.3.x to get a feel for C++0x for myself.

In your case, how will the next C++ standard affect the way you do concurrency-aware programming? Do you think the new features will really be helpful or do you think there are still many things lacking? I'd love to hear what you think!

0 comments: