开发者

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

开发者 https://www.devze.com 2023-02-02 09:04 出处:网络
Suppose I have a function that tries to protect a global counter using this code: static MyCriticalSectionWrapper lock;开发者_运维技巧

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?


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


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.)


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;


That depends on your lock implementation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号