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()() 函数的地方。

相关推荐
码匠许师傅13 小时前
【设计模式精讲】14.外观模式(Facade)
c++·设计模式·uml·外观模式
xxwxx__15 小时前
C++ list 深度解析:从使用原理到模拟实现
开发语言·c++·list
Chester_199915 小时前
CSP202303C.LDAP
开发语言·c++·蓝桥杯·stl
j7~16 小时前
【C++】《unordered系列关联式容器以及哈希底层、哈希冲突、闭散列与开散列完整解析》
c++·哈希算法·开散列·闭散列·unordered_map·unordered_set·哈希底层结构
2402_8828938617 小时前
封装红黑树实现map和set —— 从源码到模拟实现
c++·set·map
神仙别闹18 小时前
基于C++ MFC 实现的智慧公交系统
开发语言·c++·mfc
dear_bi_MyOnly19 小时前
函数模块化:企业级项目高效之道
c++·后端·学习
码匠许师傅19 小时前
【设计模式精讲】13.装饰器模式(Decorator)
c++·设计模式·uml·装饰器模式
OPEN-F19 小时前
C++综合实战:面向对象图书管理系统
开发语言·c++
NeoGressAI外贸数字化20 小时前
外贸独立站零询盘排查:从 Google Search Console 到 PageSpeed 的技术实操
开发语言·c++