Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is construction of static function-scope object thread-safe?

Tags:

c++

Suppose I have a function that tries to protect a global counter using this code:

 static MyCriticalSectionWrapper lock;
 lock.Enter();
 counter = ++m_counter;
 lock.Leave();

IS there a chance that two threads will invoke the lock's constructor? What is the safe way to achieve this goal?

like image 257
Alex Emelianov Avatar asked Oct 13 '22 18:10

Alex Emelianov


1 Answers

The creation of the lock object itself is not thread safe. Depending on the compiler, you might have multiple independent lock objects created if multiple threads enter the function at (nearly) the same time.

The solution to this problem is to use:

  • OS guaranteed one time intialization (for the lock object)
  • Double-checked locking (Assuming it is safe for your particular case)
  • A thread safe singleton for the lock object
  • For your specific example, you may be able to use a thread safe interlocked (e.g., the InterlockedIncrement() function for Windows) operation for the increment and avoid locking altogether
like image 107
Michael Goldshteyn Avatar answered Oct 18 '22 02:10

Michael Goldshteyn