给定一个班级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 Code Online (Sandbox Code Playgroud)
当我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
}
Run Code Online (Sandbox Code Playgroud)
我不熟悉对象如何在 C++ 线程中工作,所以我希望有一个解决方案