Monday, June 4, 2007

C++ Threads

There is a very good talk by Lawrence Crowl on the upcoming threading changes to C++. I wrote a brief entry about his talk on C++0x (where they are hoping for x < 10). They have developed heavily on the work done for the Java model, so that they could resolve some of the C++ absurdities that inevitably occur. Hans Boehm, who was heavily involved in the Java effort, has been leading the effort.

One neat feature is the proposed atomic keyword. All accesses to a variable declared atomic will be, obviously enough, atomic. It will support features like compare-and-swap and atomic increment (of numerical types). The neat part is that this will work for more than just scalar types (as it does in most current systems). You can declare an entire object to be atomic, and update it all at once. Efficiency depends, of course, on whether the hardware supports such operations, or they need to be emulated in software.

As this is C++, they felt the need to overload operators for atomic support. For example, if you have an atomic int v, then code that reads v++ performs an atomic increment. This is reasonably intuitive, and has been the source of confusion for some Java programmers with volatile variables.

The problem is that in order to support this, they have to start having some really messy details. For example, the semantics of the assignment operator (=) usually involve a load followed by a store, and for the operator to return whatever the result of evaluating the RHS was. This makes assignment a two-step process.

Why is this tricky? Let's say we have two atomic integers, a and b. If you say something like a += 4, you simply perform a machine-level atomic increment of a by 4, and it works trivially. On the other hand, if you have a = b, then you would have to assign the value of b to a without letting the value of b change while you are changing a. This is not supported by most architectures. So, they allow overloading of the assignment operator, but only if there is no atomic variable on the RHS of the equation. How ugly is that?

There are a lot of other interesting details in the talk. It is definitely recommended.

No comments: