【发布时间】:2022-10-18 21:31:31
【问题描述】:
我正在开发一个计时器类以在不同的线程上执行操作,下面的示例代码是另一个 SO 问题HERE 的副本
#include <thread>
#include <chrono>
#include <functional>
class Timer
{
public:
~Timer();
Timer() noexcept;
typedef std::chrono::milliseconds Interval;
typedef std::function<void(void)> Timeout;
public:
void start(const Interval& interval, const Timeout& timeout);
void stop();
private:
std::thread mThread; /** Timer thread */
bool mRunning = false; /** Timer status */
};
带有注释的实现,其中将出现问题:
Timer::~Timer()
{
}
Timer::Timer() noexcept
{
}
void Timer::start(const Interval& interval, const Timeout& timeout)
{
mRunning = true;
mThread = std::thread([&]()
{
while (mRunning == true)
{
std::this_thread::sleep_for(interval);
// std::abort will be called here
timeout();
}
});
}
void Timer::stop()
{
mRunning = false;
mThread.join();
}
测试定时器的示例:
#include <iostream>
int main()
{
Timer tm;
tm.start(std::chrono::milliseconds(1000), []
{
std::cout << "Hello!" << std::endl;
});
std::this_thread::sleep_for(std::chrono::seconds(4));
tm.stop();
}
我无法理解为什么在 lambda 中执行 std::function 时会调用 std::abort,我该如何解决这个问题?
【问题讨论】:
-
您正在保存对临时对象的引用,该对象在您有机会调用
timeout之前被销毁。 -
不过,这不是唯一的问题:您还需要将
mRunning设为原子。
标签: c++ multithreading timer