c++ - 基于没有 Boost 的标准模板库的 TimerCallback 函数

标签 c++ stl timer

是否有使用 STL 实现的 TimerCallback 库。我无法将 Boost 依赖项引入我的项目。

定时器到期时应该能够回调注册的函数。

最佳答案

标准库中没有特定的计时器,但很容易实现一个:

#include <thread>

template <typename Duration, typename Function>
void timer(Duration const & d, Function const & f)
{
    std::thread([d,f](){
        std::this_thread::sleep_for(d);
        f();
    }).detach();
}

使用示例:

#include <chrono>
#include <iostream>

void hello() {std::cout << "Hello!\n";}

int main()
{
    timer(std::chrono::seconds(5), &hello);
    std::cout << "Launched\n";
    std::this_thread::sleep_for(std::chrono::seconds(10));
}

请注意该函数是在另一个线程上调用的,因此请确保它访问的任何数据都受到适当保护。

关于c++ - 基于没有 Boost 的标准模板库的 TimerCallback 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11763786/

相关文章:

android - std::map 链接器错误 ndk r8c with APP_STL := gnuSTL_static

c++ - 错误 C2664 : 'void std::vector<_Ty>::push_back(_Ty&&)' : cannot convert parameter 1 from 'Node<T> *' to 'Node<T>&&'

java - 如何在 Java GUI 中重置计时器并在停止后显示消息

c - 在 C 中实现/模拟具有 20Mhz 时钟和 1024 预分频器的 16 位计数器

javascript - 如何暂停和恢复 javascript 计时器

c++ - 如何在无向图中找到两条边的相等性?

c++ - 无需安装 Oracle 客户端或即时客户端的 Oracle C++ 连接

c++ - 在类C++中的并集内初始化数组

c++ - 有关实现游戏多人游戏的信息?

c++ - 尝试解析保存为std::string的大文本文件