Friday, July 18, 2014

C++11 Memory Model

What is the most interesting and promising feature in C++11? Many of you might say it's the rvalue semantics including move and perfect forward concepts. But I don't think so.

Let me clarify what I mean. Definitely, rvalue semantics is a step forward. But it's not the most advanced and interesting part of the standard. The reason is that it doesn't contain something new. Forwarding is like a syntactic sugar, it allows avoiding unnecessary usage of overloaded functions. Move semantics had been introduced before C++11, for example, in Ultimate++ framework, transfer semantics. So, it's like a syntax evolution to deeper improve performance when return value optimization cannot be applied.

Meanwhile the memory model is another story. It resolves one of the most sophisticated problems: how to obtain common denominator for very different hardware processor models with different assembler instructions. It's very complicated problem. You have to know about every platform to create such denominator. And I would say that it has been resolved perfectly.

Wait, wait, wait. Most of readers might raise an objection against "perfect solution". It's the most complex part of the standard. It's true. But the problem itself is much more complicated. So solution from the problem statement point of view is much simpler.

Solution is great indeed. It provides an abstraction that allows to create highly portable and still very efficient applications using appropriate atomic instructions on any platform: from x86 to modern ARM and DEC Alpha (with special consume/release semantics, as if DEC and ARM platforms like relaxing). Finally, memory model of next generation of ARM processor is going to have special atomic sequential consistency instructions providing better performance in most cases. It's the case when hardware pays attention to software needs. It's fundamental model that has far-reaching consequences. And it's amazing!

I'm very expecting that in the nearest future any lock-free and wait-free articles will contain detailed description of memory ordering for all involved atomic operations.