TimerCallback函数基于没有Boost的标准模板库
TimerCallback function based on Standard Template LIbrary without Boost
是否存在使用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 << "Launchedn";
std::this_thread::sleep_for(std::chrono::seconds(10));
}
请注意,该函数是在另一个线程上调用的,因此请确保它访问的任何数据都受到适当的保护。
相关文章:
- 使用宏编译时使用用户定义的数学函数,或者仅使用 c++ 中标准数学库中的函数
- C++规范是否特别对待标准 t 库?
- Boost.Python :C++模板类型匹配的嵌套命名空间
- 覆盖程序中的标准 C 库函数C++
- DLLexport 类模板实例(专用化),减少了仅标头模板库的编译时间
- 猫鼬 - 包含标准C++库文件时出错
- TimerCallback函数基于没有Boost的标准模板库
- 如何在标准模板库中实现字符串的深度同步
- 模板库的编译器内存消耗(boost + 特征)
- 标准模板库列表 - 双重链接或循环链接
- 没有运算符"="与这些操作数匹配 - 标准模板库中的迭代器
- 如何使用boost/标准库在C++中读取/写入图像
- 为什么C++标准模板库不包含矢量的"sort"成员函数?
- 如何在标准模板库中分配/取消分配对象
- 使用标准模板库中的堆栈
- 标准模板库,矢量和语法错误
- 使用标准c++库vector作为底层实现创建Set模板类
- C++ 标准模板库的智能感知错误:<error-type>*?
- 模仿从标准模板库中删除的函数无法正常工作
- 使用标准模板库list或vector和multimap创建电话号码簿