假设我有一个名为 foo
的类,它在一个线程中执行一些任务。我想在我认为合适的时候开始和停止这个任务。我的代码如下:
class foo
{
public:
foo() {};
~foo() {};
void start_thread() {
thread_active = true;
the_thread = std::thread(&foo::execute, this);
}
void stop_thread() {
thread_active = false;
the_thread.join();
}
private:
void execute() {
while (thread_active)
std::cout << "executing...\n";
}
std::thread the_thread;
bool thread_active;
};
我这样调用它的地方:
int main()
{
foo bar;
bar.start_thread();
Sleep(1000);
bar.stop_thread();
}
这样做安全吗?
最佳答案
不,这不是一种安全的方式。
原因是thread_active
成员在读写时多个线程没有同步访问,你应该声明它std::atomic_bool
或者使用其他形式同步。
关于c++ - 这是启动和停止线程的安全方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60243116/