« Darwinian Software Development | Main | A Tiger Released »

August 17, 2004

Comments

Jonas

I totally agree on the RAII idiom and the Lock is a "beautiful" example BUT:

Having a function static

static CriticalSection s_criticalsection;

in your multithreaded code how does that work??? You need a lock around the constructor of that one and it's catch 22. Isn't function statics initialized on the first "entry" of a thread?

So when I use this idiom, I make the CriticalSection "file" static so the constructor will be run by the CRT init.

I don't know if the above is different between compilers?

Thanks
/Jonas

Jonathan Dodds

Thanks Jonas.

You are completely correct. I wanted to keep the example simple but I made it too simple. Its bad code and I need to change it.

Thanks for seeing the error and telling me about it. I appreciate the constructive feedback.

anon_coder

Hi Jonathan
great work, can you please update the example code with "static functions"and with "static CriticalSection s_criticalsection;" like Jonas's above comment..
good work,very helpful
thanks a lot

Jonathan Dodds

anon_coder,
I updated the example code in May to remove the function static.

The original example code was something like:


bool Process( )
{
static CriticalSection s_criticalsection;

CSLock lock(s_criticalsection);

// do some stuff

}


Using a function static like this is unsafe with multiple threads. There is a potential for a race condition. The s_criticalsection object is constructed on the first entry into the function. If two (or more) threads enter the function concurrently for the first entry each thread may construct its own s_criticalsection object.

A solution is to make s_criticalsection a file static instead of a function static:


static CriticalSection s_criticalsection;
bool Process( )
{
CSLock lock(s_criticalsection);

// do some stuff

}


In the file static version you pay for the construction of s_criticalsection regardless of whether Process() is called.

When I revised the example code I used a class example because I think it's a more interesting case and because I had originally intended to make a point about lazy construction.

Arno Nymous

Congratulations, very good article! You even make copy constructor and operator= private. Every C++ programmer should know that. Found this article through a link in another RAII article: http://www.codeproject.com/cpp/RAIIFactory.asp

The comments to this entry are closed.