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

相关推荐
阿林学习计算机27 分钟前
C++11特性
c++
Elias不吃糖1 小时前
NebulaChat:C++ 高并发聊天室服务端
开发语言·c++·redis·sql·项目文档
帅中的小灰灰1 小时前
C++编程策略设计模式
开发语言·c++·设计模式
是小胡嘛2 小时前
华为云CentOS系统中运行http服务器无响应
linux·服务器·c++·http·centos·华为云
福尔摩斯张3 小时前
C语言核心:string函数族处理与递归实战
c语言·开发语言·数据结构·c++·算法·c#
江澎涌3 小时前
JHandler——一套简单易用的 C++ 事件循环机制
android·c++·harmonyos
liu****3 小时前
5.C语言数组
c语言·开发语言·c++
毛甘木3 小时前
Unity MonoPInvokeCallback 使用教程
c++·unity
吗~喽3 小时前
【LeetCode】滑动窗口_水果成篮_C++
c++·算法·leetcode
BestOrNothing_20154 小时前
【C++基础】Day 4:关键字之 new、malloc、constexpr、const、extern及static
c++·八股文·static·extern·new与malloc·constexpr与const