假设我有一个名为 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>
。 - Werner Henzex86
和arm
上运行。 - Tarek Dakhran