我正在尝试使用经典方法实现基本计时器:start()和stop().我正在使用带有std :: thread和std :: chrono的c ++ 11.
我创建并启动了一个显示"Hello!"的Timer对象.每一秒,然后与其他线程我试图停止计时器,但我不能.计时器永不停止.
我认为问题在于th.join()[*]在线程完成之前停止执行,但是当我删除th.join()行时,程序显然在计时器开始计数之前完成.
所以,我的问题是如何在不停止其他线程的情况下运行线程?
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
class Timer
{
thread th;
bool running = false;
public:
typedef std::chrono::milliseconds Interval;
typedef std::function<void(void)> Timeout;
void start(const Interval &interval,
const Timeout &timeout)
{
running = true;
th = thread([=]()
{
while (running == true) {
this_thread::sleep_for(interval);
timeout();
}
});
// [*]
th.join();
}
void stop()
{
running = false;
}
};
int main(void)
{
Timer tHello; …Run Code Online (Sandbox Code Playgroud)