C++ 在类构造函数中启动std::线程是否是线程安全的?
所以我有一个类似这样的代码(C++11): 我的问题是,我理解得好吗?如何修复此代码?我想让构造函数创建线程机制C++ 在类构造函数中启动std::线程是否是线程安全的?,c++,multithreading,atomic,C++,Multithreading,Atomic,所以我有一个类似这样的代码(C++11): 我的问题是,我理解得好吗?如何修复此代码?我想让构造函数创建线程机制 谢谢你基本上,如果多个线程修改数据,你需要在main()中使用同步原语,比如std::mutex,如果我不使用f->AddToVec(78);f->setter(67);调用,我的代码是OKY?嗯,你错拼了“StTrLoCo”,一方面:(多线程是硬的。你需要在动作中阅读像C++并发的书籍,或者做一些程序,至少了解基本原理。否则,你会得到损坏的数据或死锁。 class Foo {
谢谢你基本上,如果多个线程修改数据,你需要在main()中使用同步原语,比如
std::mutex
,如果我不使用f->AddToVec(78);f->setter(67);调用,我的代码是OKY?嗯,你错拼了“StTrLoCo”,一方面:(多线程是硬的。你需要在动作中阅读像C++并发的书籍,或者做一些程序,至少了解基本原理。否则,你会得到损坏的数据或死锁。
class Foo
{
private:
std::vector<int> vec;
int val;
std::thread Foo_thread;
public:
Foo();
void StartLoop();
void WaitTermination() { this->Foo_thread.join(); }
void AddToVec(int dummy) { vec.push_back(dummy); }
void setter(int val) { this->val = val; }
};
void Foo::StartLoop()
{
while (true)
{
// some code . . .
this->vec.push_back(something);
}
}
Foo::Foo()
{
this->Foo_thread = std::thread(&Foo:SartLoop, this);
}
int main()
{
Foo* f = new Foo{};
f->WaitTermination();
}
int main()
{
Foo* f = new Foo{};
f->AddToVec(78); // at this point, we modify the private vec member, both from the main thread and in the std::thread, if I undersand well
f->setter(67); // same problem, however it's easier to declare val as std::atomic<int>, but the above one is really problematic
f->WaitTermination();
}