Alex Emelianov
Alex Emelianov

Reputation: 1274

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

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?

Upvotes: 5

Views: 751

Answers (4)

Chris Bennet
Chris Bennet

Reputation: 617

Original sample code:

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

I realize that the counter code is probably just a placeholder, however if it is actually what you trying to do you could use the Windows function "InterlockedIncrement()" to accomplish this. Example:

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

Upvotes: 0

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74400

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

Upvotes: 4

9dan
9dan

Reputation: 4282

Constructor invoke can be implementation and/or execution environment dependent, but this isn't a scoped_lock so not an issue.

Main operation is properly guarded against multi thread access I think.

(You know, global for global, function static for function static. That lock variable must be defined in the same scope with the guarded object.)

Upvotes: 1

wilhelmtell
wilhelmtell

Reputation: 58685

That depends on your lock implementation.

Upvotes: -1

Related Questions