user73554
user73554

Reputation: 103

Thread-safety for static class data members

Can I assume thread-safety for static class data members in C++? In the following example, is SetCounter thread-safe?

class Foo {
public:
  static void SetCounter(int c) { counter = c; }  
private:
  static int counter = 0;
}

Upvotes: 1

Views: 641

Answers (1)

SteveK
SteveK

Reputation: 995

Thread-safety refers to making actions independent of other actions to avoid race conditions. If you have 2 threads, one calling SetCounter(1) and the other calling SetCounter(2), you can't guarantee what counter will be set to. You'd need to use a mutex/lock on the value to prevent it from being modified by other threads. If you're using libraries like boost, you can refer to the Synchronization page. Otherwise, use your own mutex to toggle whether it's locked or unlocked.

Upvotes: 1

Related Questions