所以这个共享对象是这样的(只是为了演示,不是工作的):
class Shared{
int var1;
int var2;
public:
void setter1(int var){
var1=var;
}
void setter2(int var){
var2=var;
}
}
并且 thread1
可以执行 shared->setter1(3)
而 thread2
可以执行 shared->setter2(2)
同时没有任何竞争条件或问题?
最佳答案
是的,您可以在两个独立的线程中访问 Shared
对象的各个子对象而无需同步,这不会成为竞争条件。 cppreference上给出了外行的解释,这里是部分引用:
Different threads of execution are always allowed to access (read and modify) different memory locations concurrently, with no interference and no synchronization requirements.
但是,请注意 false sharing !您的代码似乎很容易出现这种情况。
关于c++ - 多线程写入C++中共享对象的不同变量是否可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58068460/