Is building an object of a static function-object a thread-safe?

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

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

Is it likely that two threads will call the constructor lock? What is the safest way to achieve this?

+5
source share
4 answers

Creating the lock object itself is not thread safe. Depending on the compiler, you can create several independent locking objects if several threads enter the function at (almost) at the same time.

The solution to this problem is to use:

  • OS guaranteed a one-time initialization (for a lock object)
  • (, )
  • (, InterlockedIncrement() Windows)
+4

invoke / , scoped_lock, .

, .

( , , static. .)

+1

Original sample code:

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

I understand that the oncoming code is probably just a placeholder, however if this is really what you are trying to do, you can use the Windows function "InterlockedIncrement ()" to accomplish this. Example:

 // atomic increment for thread safety
 InterlockedIncrement(&m_counter);
 counter = m_counter;
0
source

It depends on your implementation of the lock.

-1
source

All Articles