[英]Thread Safety and static functions
Let's suppose I have a : 我想我有一个:
class base
{
base(){f(this);};
static void f(base * b) {(b->d)++;};
int d;
};
Now if on 2 separate threads I create an object of type base, would method f
be considered thread safe? 现在如果在2个单独的线程上我创建了一个base类型的对象,方法f
会被认为是线程安全吗? I am asking this question because usually from what I know is that for a method to be thread safe it should not use static members nor global variables. 我问这个问题,因为通常从我所知道的是,对于一个线程安全的方法,它不应该使用静态成员或全局变量。 But as you can see from the above example I decided not to make variable d
static, instead I call it through the running instance of base. 但是正如你从上面的例子中看到的那样,我决定不将变量d
设为静态,而是通过运行的base实例来调用它。
Also, I think I don't need to protect this line : (b->d)++;
另外,我认为我不需要保护这一行: (b->d)++;
with a mutex since each thread will have a separate instance of base and of variable d. 使用互斥锁,因为每个线程都有一个单独的base和变量d的实例。
Am I correct in my analysis? 我的分析是否正确? is there anything I should be careful about? 有什么我应该小心的吗?
Yes, your constructor is thread safe, because it accesses only instance variables (specifically, d
). 是的,您的构造函数是线程安全的,因为它只访问实例变量(特别是d
)。 It does exhibit undefined behavior, because it reads from uninitialized d
to perform the increment, but that has nothing to do with thread safety. 它确实表现出未定义的行为,因为它从未初始化的d
读取以执行增量,但这与线程安全无关。
Here is how you can fix undefined behavior: 以下是修复未定义行为的方法:
base(): d(0) {f(this);};
Now that d
is initialized in the initializer list, your program behaves in a predictable way. 现在d
在初始化列表中初始化,您的程序以可预测的方式运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.