C++笔记之将定时器加入向量并设置定时器的ID为i

C++笔记之将定时器加入向量并设置定时器的ID为i

code review!

文章目录


运行

代码

cpp 复制代码
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>

// 定义定时器类
class Timer {
  public:
    Timer(int id, std::chrono::seconds interval) : id(id), interval(interval) {}
    void operator()() {
        std::this_thread::sleep_for(std::chrono::seconds(interval));
        std::cout << "Timer " << id << " expired!" << std::endl;
    }

  private:
    int id;
    std::chrono::seconds interval;
};

// 定义一个函数,用于将定时器加入向量并设置定时器的ID为i
void addTimer(std::vector<Timer> &timers, int i, std::chrono::seconds interval) {
    Timer timer(i, interval);
    timers.push_back(timer);
}

int main() {
    // 创建一个包含3个定时器的向量
    std::vector<Timer> timers;
    addTimer(timers, 1, std::chrono::seconds(1));
    addTimer(timers, 2, std::chrono::seconds(2));
    addTimer(timers, 3, std::chrono::seconds(7));

    // 启动定时器并等待它们到期
    for (auto &timer : timers) {
        std::thread t(std::ref(timer));
        t.detach(); // 将定时器线程分离,使其在后台运行
    }
    std::this_thread::sleep_for(std::chrono::seconds(10)); // 等待10秒钟,使所有定时器都有足够的时间到期

    return 0;
}

关于代码中的void operator()()

Timer timer(i, interval); 这一行实际上是在创建 Timer 对象,并且在这个过程中没有直接使用了 operator()() 函数调用运算符。
operator()() 函数调用运算符的使用方式是通过将 Timer 对象传递给 std::thread 的构造函数来实现的,如下所示:

cpp 复制代码
std::thread t(std::ref(timer));

这里的 timer 是一个 Timer 类型的对象。通过传递 std::ref(timer)std::thread 构造函数,你实际上在创建一个新的线程,并在这个新线程中调用了 timer 对象的 operator()() 函数。这就是代码中使用 operator()() 函数的地方。

相关推荐
MSTcheng.1 小时前
CANN ops-math算子的跨平台适配与硬件抽象层设计
c++·mfc
code monkey.1 小时前
【Linux之旅】Linux 进程间通信(IPC)全解析:从管道到共享内存,吃透进程协作核心
linux·c++·ipc
薛定谔的猫喵喵1 小时前
基于C++ Qt的唐代诗歌查询系统设计与实现
c++·qt·sqlite
阿昭L1 小时前
C++异常处理机制反汇编(三):32位下的异常结构分析
c++·windows·逆向工程
Cinema KI1 小时前
C++11(下) 入门三部曲终章(基础篇):夯实语法,解锁基础编程能力
开发语言·c++
燃于AC之乐1 小时前
深入解剖STL List:从源码剖析到相关接口实现
c++·stl·list·源码剖析·底层实现
汉克老师1 小时前
GESP2025年6月认证C++二级( 第一部分选择题(9-15))
c++·循环结构·求余·gesp二级·gesp2级·整除、
不想睡觉_1 小时前
优先队列priority_queue
c++·算法
rainbow688912 小时前
EffectiveC++入门:四大习惯提升代码质量
c++
秋邱12 小时前
用 Python 写出 C++ 的性能?用CANN中PyPTO 算子开发硬核上手指南
开发语言·c++·python