直接上代码
#include <iostream>
#include <chrono>
#include <future>
#include <thread>
#include <mutex>
#include <condition_variable>
class GpDeadTimer
{
public:
GpDeadTimer(){}
~GpDeadTimer(){}
std::future<void> asyncWait(int mesc, std::function<void()> callback_fun)
{
return std::async(std::launch::async, [this, mesc, callback_fun](){
std::unique_lock<std::mutex> lck(timer_mtx_);
stop_timer_ = false;
if (!timer_cv_.wait_for(lck, std::chrono::milliseconds(mesc), [this]{ return stop_timer_ == true; }))
{
callback_fun();
}
else
{
std::cout << "operator break\n";
}
});
}
void cancel()
{
{
std::lock_guard<std::mutex> lck(timer_mtx_);
stop_timer_ = true;
}
timer_cv_.notify_all();
}
private:
std::mutex timer_mtx_;
std::condition_variable timer_cv_;
std::atomic<bool> stop_timer_{true};
};
测试1
测试2