[英]Is this a safe way to start and stop a thread?
Say I have a class called foo
which executes some task in a thread.假设我有一个名为foo
的类,它在线程中执行一些任务。 I want to start and stop this task as I see fit.我想按照我认为合适的方式开始和停止这项任务。 My code is the following:我的代码如下:
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;
};
where I call it like so:我这样称呼它:
int main()
{
foo bar;
bar.start_thread();
Sleep(1000);
bar.stop_thread();
}
Is this a safe way to do so?这是一种安全的方法吗?
No, this is not a safe way.不,这不是一种安全的方式。
The reason is that the thread_active
member is accessed without synchronization from multiple threads in read and write, you should declare it std::atomic_bool
or use some other form of synchronization.原因是thread_active
成员在读取和写入时没有从多个线程同步访问,您应该声明它std::atomic_bool
或使用某种其他形式的同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.