如何从线程正在使用的对象实例调用方法?
给定一个班级MyTimer.h:
#include <iostream>
using namespace std;
class MyTimer {
private:
bool active = false;
public:
void run() {
active = true;
while (active) {
cout << "I am runningn";
Sleep(1000);
};
}
void stop() {
active = false;
}
};
当我run()在线程中执行方法时,它会"I am running"每秒运行一次循环打印。
我想通过执行stop()which will set activetofalse并且应该停止循环来停止循环,但是它不会停止并继续打印"I am running"。
#include "MyTimer.h"
#include <thread>
int main(){
MyTimer myTimer;
std::thread th(&MyTimer::run, myTimer);
Sleep(5000);
myTimer.stop(); // It does not stop :(
while (true); // Keeping this thread running
}
我不熟悉对象如何在 C++ 线程中工作,所以我希望有一个解决方案
回答
你有三个问题:
-
active应声明为std::atomic <bool>. 没有这个,在一个线程中所做的更改可能不会被另一个线程看到(编译器可能会优化检查)。 -
std::thread th(&MyTimer::run, myTimer);副本myTimer。相反,您想要std::thread th(&MyTimer::run, &myTimer);. -
while (true);更好地表示为th.join (),因为 (a) 这不是繁忙的循环,并且 (b) 它允许程序在线程终止时退出。
现场演示