我正在尝试使用经典方法:start()和stop()实现一个基本计时器。我使用c++11中的std::thread和std::chrono。
- Start方法。创建一个新线程休眠一段时间,然后执行给定的std::function。只要'running'标志为true,就重复此过程。
- Stop方法。将'running'标志设置为false。
我创建并启动了一个Timer对象,每秒钟显示“Hello!”一次,然后我用另一个线程尝试停止计时器,但我无法停止计时器。计时器永远不会停止。
我认为问题出在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;
tHello.start(chrono::milliseconds(1000),
[]()
{
cout << "Hello!" << endl;
});
thread th([&]()
{
this_thread::sleep_for(chrono::seconds(2));
tHello.stop();
});
th.join();
return 0;
}
输出:
Hello!
Hello!
...
...
...
Hello!