omegasbk
omegasbk

Reputation: 906

C++ thready safety of a static member variable

For example, I have this class:

class Example
{
public: 
    static int m_test;
}

I have threads A and B both using this static member variable. Is this member variable thread safe somewhere under the hub?

I would assume it is not, since it is statically allocated and therefore both threads would be accessing the same memory location, possibly causing collisions. Is that correct or there is some hidden mechanism that makes this static member thread-safe?

Upvotes: 1

Views: 239

Answers (2)

Daniel Langr
Daniel Langr

Reputation: 23497

It is safe if both threads just read that variable. If at least one updates it, then it's a data race -> undefined behavior.

Hidden mechanism are atomic operations. E.g., via making this variable of std::atomic<int> type in C++11.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234715

No it is not thread safe insofar there is no built-in mechanism to obviate data races.

static std::atomic<int> m_test; would be though.

Note that you also have thread_local as a storage duration too - not of use to you in this instance - but if you had that rather than static then every thread would get their own m_test.

Upvotes: 2

Related Questions