[英]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. 我有线程A和B都使用这个静态成员变量。 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?
这是正确的还是有一些隐藏机制使这个静态成员线程安全?
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
. 请注意,你也有
thread_local
作为存储持续时间 - 在这个例子中没有使用 - 但如果你有这个而不是static
那么每个线程都会获得自己的m_test
。
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. 隐藏机制是原子操作。 Eg, via making this variable of
std::atomic<int>
type in C++11. 例如,通过在C ++ 11中创建
std::atomic<int>
类型的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.