给定一个类MyTimer.h
:
#include <iostream>
using namespace std;
class MyTimer {
private:
bool active = false;
public:
void run() {
active = true;
while (active) {
cout << "I am running\n";
Sleep(1000);
};
}
void stop() {
active = false;
}
};
当我run()
在线程中执行方法时,它将"I am running"
每秒运行一次循环打印。
我想通过执行stop()
which will set active
to false
and that 应该停止循环来停止循环,但是它不会停止并且它会继续打印"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++ 线程中的工作方式,所以我希望有一个解决方案