I have a doubt about a third party library which is essentially a wrapper around pthread.
This is how its join function is implemented:
bool Join() throw ()
{
ThreadState s;
{
CCriticalSectionLock L(m_CS);
s = m_CurrentThreadState;
}
if (s == Started) {...}
}
Shouldn’t have the if (s == Started) {...} code been put inside the block where the lock is defined?
As it is, the critical section includes a variable assignment only, that being an elementary operation would not have needed it.
Thank you.
The critical section ensures that reading the shared variable (
m_CurrentThreadState) is done atomically. C++ gives no guarantee that elementary operations are atomic, although these days one could usestd::atomicrather than a lock.Whether or not the lock needs to be maintained for whatever logic follows that access is a question that would require careful analysis of how the threads interact. Hopefully, the library author did that analysis, and determined that it was safe to act on the value without maintaining the lock.