[英]Thread-safety for static class data members
Can I assume thread-safety for static class data members in C++? 我可以为C ++中的静态类数据成员承担线程安全性吗? In the following example, is SetCounter thread-safe?
在下面的示例中,SetCounter线程安全吗?
class Foo {
public:
static void SetCounter(int c) { counter = c; }
private:
static int counter = 0;
}
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. 如果您有2个线程,一个线程调用
SetCounter(1)
,另一个线程调用SetCounter(2)
,则不能保证将counter
设置为哪个线程。 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 .
如果您使用的是Boost等库,则可以参考同步页面 。 Otherwise, use your own mutex to toggle whether it's locked or unlocked.
否则,请使用您自己的互斥锁来切换是锁定还是解锁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.