Hi,
I was going through this article
http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx
This talks about "C++ scoped static initialization is not thread-safe, on purpose!"
One of the resolutions is to use to critical section to avoid race condition.
My question is what if in any program, critical section itself is static, then there will be thread safety issue, any pointers/ideas how avoid this condition
Thanks!

Thread Safety in C++ code
Rober7
Critical section objects are initialized as the parameter to InitializeCriticalSection, and not through assignment. Therefore, static initialization isn't really the main issue.
Given a function such as
we are at the mercy of another problem. Calling InitializeCriticalSection on an already created critical section causes undefined behavior. So, if you are to include the initialization to the function itself, you need a second static variable to flag wheter or not the section has already been initialized.
This takes us one step further, but the if construct is obviously not thread safe, and undefined behavior awaits once more. To solve the issue, we can look to InterlockedIncrement, in a manner such as this.
From the top:
Being of static intrinsic type, initialized will be set to 0, with no race condition (it doesn't happen inside the function). The same goes for the critical section. No code, no problem.
The interesting part is InterlockedIncrement. This function will use a lock prefix to assure that no two calls, "simultaneous" or not, will return the same number. We can therefore safely see if the return value is 1, which would indicate that it was previously 0 (duh), and that the critical section has not been initialized. After calling ICS, we reset initialized to 1, to avoid problems caused by an type overflow (if you should happen to call the function 2^32 times).
Having done that, we're all good enter the critical section, and do whatever needs to be done.
This approach is however not the best one seen from neither a design point of view, or with regard to efficiency. You will be getting a bunch of extra operations for each call to foo(), which wouldn't be needed if the critical section was moved outside the function scope. But you do get what you ask for :)
none33333333