promise定时器
promise可以用于实现定时器,需要注意哈,对同一个promise进行重复多次set_value会崩溃的
C++ |
---|
| #include <promise>
#include <thread>
#include <memory>
#include <chrono>
// 定义一个promise变量用于标识超时与是否执行成功
std::promise<bool> flag;
// 这个running标识定时器是否在运行
bool running;
// 另启动一个线程用于定时
std::unique_ptr<std::thread> timerThread;
// 则在主线程需要启动定时器时
timerThread = std::make_unique<std::thread>(func);
// 线程中处理类似为
void func()
{
running = true;
auto future = flag.get_future();
// 定时3s
std::future_statue status = future.wait_for(std::chrono::seconds(3));
// 根据返回值判断
switch (status) {
case std::future_status::timeout:
// 超时了
// do sth.
break;
case std::future_status::ready:
// 未超时,future中获取到了一个bool值,这里可以更进一步根据future是否为true来判断定时的任务是否成功
bool ret = future.get();
// 根据返回值
// do sth.
break;
default:
break;
}
running = false;
}
// 然后在成功的线程就这样
void success()
{
if (running) {
flag.set_value(true);
}
}
// 失败的线程就这样
void fail()
{
if (running) {
flag.set_value(false);
}
}
// 主线程退出时同样
void exit()
{
if (timerThread) {
if (running) {
flag.set_value(false);
}
timerThread->join();
timerThraed.reset();
}
}
// ATTENTION
// future不能被多次set和get
|