C ++ 11方式来创建可以被“停止”的定时器。如果需要的话 [英] C++11 way to create a timer that can be "stopped" if needed

查看:223
本文介绍了C ++ 11方式来创建可以被“停止”的定时器。如果需要的话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须每X秒调用一个函数来显示长时间运行的函数的进度,但是如果函数在进度更新的下一个tick之前结束,我想删除通知。我刚刚开始使用C ++ 11,我不知道是否有一个方法来实现这个使用正确的C ++ 11语法/对象。

I have to call a function every X seconds to show the progress of a long running function, but i want to drop the notification if the function ends before the next tick of the progress update. I just recently started using C++11 and i don't know if there is a way to achieve this using proper c++11 syntax/objects.

基本上,我试图找出是否有一种方法来访问与posix函数公开的相同的功能 timer_create timer_delete 使用C ++ 11线程和异步函数。

Basically, I am trying to figure out if there is a way to access the same features as those exposed by the posix functions timer_create and timer_delete using the C++11 threads and async functions.

我发现这个问题如何使用C ++ 11创建定时器事件?,它涵盖了我需要的几乎所有的东西,但我无法确定是否有一种方法停止异步调用一旦是提交。

I did find this question "How to create timer events using C++ 11?", which covers almost everything i need but i couldn't figure out if there's a way to stop the async call once it is "submitted".

现在可以在C ++ 11中执行吗?

Is this possible now in C++11?

推荐答案

简介>

简单的解决方案是让计时器设置为在 时间单位可以 潜在地睡眠,但是如果某事中断了睡眠,我们不应该执行任务<

Introduction

The simple solution is to make it so that the timer set to execute f in N time-units can potentially sleep for N time-units, but if something interrupts the sleep we should not execute the task f.

使用 std :: condition_variable 可以轻松解决这个问题,依赖于成员函数 wait_for 。如果函数未收到中断,则此函数将返回 false ,如果函数没有收到中断则返回 true

The usage of std::condition_variable can solve this issue with ease, relying on the member-function wait_for. This function will return false if the function didn't receive an interrupt, and true if it did.

待执行样本实施

这篇关于C ++ 11方式来创建可以被“停止”的定时器。如果需要的话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆