【发布时间】:2015-06-28 18:54:48
【问题描述】:
假设我有一个线程应该定期执行某些任务,但这段时间每小时 6 次 每小时 12 次(每 5 分钟一次),我经常看到控制线程的代码带有 is_running 标志的循环,每个循环都会检查该标志,如下所示:
std::atomic<bool> is_running;
void start()
{
is_running.store(true);
std::thread { thread_function }.detach();
}
void stop()
{
is_running.store(false);
}
void thread_function()
{
using namespace std::literals;
while (is_running.load())
{
// do some task...
std::this_thread::sleep_for(5min);
}
}
但是,如果调用 stop() 函数,假设在 start() 之后 1 毫秒,线程将再存活 299999 毫秒,直到它唤醒、检查标志并死亡。
我的理解正确吗?如何避免保持本应结束的线程存活(但休眠)?到目前为止,我最好的方法如下:
void thread_function()
{
using namespace std::literals;
while (is_running.load())
{
// do some task...
for (unsigned int b = 0u, e = 1500u; is_running.load() && (b != e); ++b)
{
// 1500 * 200 = 300000ms = 5min
std::this_thread::sleep_for(200ms);
}
}
}
有没有更简单直接的方法来实现这一点?
【问题讨论】:
-
每小时 6 次(每 5 分钟),每小时 12 次还是每 10 分钟? :)
-
@AlexandreLavoie 太失败了!谢谢,我会改正的! :)
-
en.cppreference.com/w/cpp/thread/condition_variable,见第一句话。不是在固定的时间内休眠,而是在这段时间内进入可发出信号的等待状态,这样其他线程仍然可以打断你
-
另一个选项是boost::basic_waitable_timer。
-
你的线程应该每 5 分钟做一次工作,还是 5 分钟后第一次工作,然后在他完成工作后再睡 5 分钟?如果第一个是你的情况,那么我会(在 Windows 上)创建一个计时器,它每 5 分钟创建一个线程来做一些工作。当创建线程开销太大时,我会使用线程池。
标签: c++ multithreading c++11 thread-sleep