Comments on Comments…part 2: Some Example Code…

I have posted some example code on GitHub showing the Shared Immutable, Exclusive Setup ideas discussed in the Comments on comments to Herb Sutter's updated GotW #6b solution (part 2) blog post to demonstrate the ideas:

My thought was to create a type that was not just a simple chunk of memory, create wrapper types to add support for the intrusive Shared Immutable, Exclusive Setup pattern discussed in the blog post that allowed for easy specification of atomic and memory order policy. Then create an example application that repeatedly creates an object having a random size of associated data on a random thread out of a random number of threads and have all other threads read this object after it has been published.

Running the example application when using an atomic and memory ordering policy that did nothing – i. e. non atomic publishing of the object with no memory ordering – would then fail randomly, whilst running when using an appropriate atomic and memory ordering policy would not.

That was the idea anyway. In practice, for the systems I had available, I could not get any detectable race conditions even with no atomic access or memory ordering.

The systems available were a VMWare workstation x86 64 bit Ubuntu Linux 12.04 virtual machine guest having multiple cores (2 processors of 4 cores) running on a Windows 8 host system having 2 Opteron 4334 processors, and a Raspberry Pi single core ARM11 system (ARMv6 architectural version). (Note: I wanted to use modern C++11 and the feature set of the Linux VM’s installed g++ - 4.6.3 – is much better than that of Microsoft Visual C++ 2012 – and matched that of the Raspberry Pi’s Raspbian installation – I did not want to spend a lot of time porting the code to various compilers!!!).

I suspect in the former case it is due to the x86 being a ‘strongly ordered’ processor. In the latter case the fact there is only one processor involved so there is no real multiprocessing may have influenced the outcome.

It may of course just be that I have not run the example application enough to have produced a detectable effect from a race condition. You cannot say for sure that a program has _not_ got a race condition just because no ill effects from race conditions have surfaced so far…ho hum.

However I think the code is still useful to show a fully worked example of what I was waffling on about.