1

给定一个类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 activeto falseand 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++ 线程中的工作方式,所以我希望有一个解决方案

4

1 回答 1

5

你有三个问题:

  1. active应声明为std::atomic <bool>. 没有这个,在一个线程中所做的更改可能不会被另一个线程看到(编译器可能会优化检查)。

  2. std::thread th(&MyTimer::run, myTimer); 副本 myTimer。相反,你想要std::thread th(&MyTimer::run, &myTimer);.

  3. while (true);更好地表示为th.join (),因为 (a) 这不会忙循环,并且 (b) 它允许程序在线程终止时退出。

现场演示

于 2021-07-11T21:14:52.357 回答