我是C++多线程的新手(显然,它与python多线程/多处理不同,因为多个线程可以在单个进程中使用多个CPU)。我知道,如果2个线程试图同时更改相同的数据,或者一个线程在另一个线程更改它的同时读取某个数据,则会出现竞争状态,但是我不确定以下情况是否需要同步:
假设我有以下类(class):
class Animal{
public:
string name_;
Animal(string name);
~Animal();
};
class Dog : public Animal{
public:
int price_;
Dog(string name, int price);
~Dog();
};
class Cat : public Animal{
public:
int price_;
Cat(string name, int price);
~Cat();
};
void do_stuff(){
Animal* a = new Dog("Foo", 3);
}
安全:
// thread 1
a->name = "Bar";
// thread 2
Dog* d = static_cast<Dog*>(a);
谢谢
请您参考如下方法:
不要去那
如果存在仅由一个线程写入/读取的数据,则根据定义它不是共享数据,也不必是全局的。
如果存在由一个线程写入并最终由另一个线程读取的数据,请使用锁,std::atomic或其他一些与同步的关系,并将其称为一天。
读取static_cast,dynamic_cast和解引用。
但最重要的是,在现代C++中,您必须使用sync-with关系或明确告诉编译器某些数据是通过
std::atomic共享的。在任何多线程程序中,甚至在玩具示例中,总有一个线程读取另一个线程写入的内容。此时,需要同步。




