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

相关推荐
Queenie_Charlie7 分钟前
数字去重(set)
数据结构·c++·set
Ayanami_Reii44 分钟前
区间不同数的个数-树状数组/线段树/莫队/主席树
数据结构·c++·算法·线段树·树状数组·主席树·莫队
大筒木老辈子1 小时前
C++笔记---并发支持库(atomic)
java·c++·笔记
zero_hz1 小时前
核心区分:用户态/内核态切换 vs. 程序阻塞
c++·io·内核态用户态
胡萝卜3.01 小时前
深入C++可调用对象:从function包装到bind参数适配的技术实现
开发语言·c++·人工智能·机器学习·bind·function·包装器
看见繁华1 小时前
C++ 高级
开发语言·c++
点云SLAM2 小时前
constexpr 和 explicit 在 C++ 中被提出的动机
开发语言·c++·explicit关键字·隐式转换·constexpr关键字·c++11/17/20
冷崖2 小时前
工厂模式-创建型
c++·设计模式
qq_310658512 小时前
mediasoup源码走读(六)——NetEQ
服务器·c++·音视频
qq_433554543 小时前
C++树形DP(树上分组背包)
c++·算法·深度优先