策劃一個(gè)網(wǎng)站網(wǎng)站推廣策劃方案
C++筆記之將定時(shí)器加入向量并設(shè)置定時(shí)器的ID為i
code review!
文章目錄
- C++筆記之將定時(shí)器加入向量并設(shè)置定時(shí)器的ID為i
- 關(guān)于代碼中的void operator()()

運(yùn)行

代碼
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>// 定義定時(shí)器類
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;
};// 定義一個(gè)函數(shù),用于將定時(shí)器加入向量并設(shè)置定時(shí)器的ID為i
void addTimer(std::vector<Timer> &timers, int i, std::chrono::seconds interval) {Timer timer(i, interval);timers.push_back(timer);
}int main() {// 創(chuàng)建一個(gè)包含3個(gè)定時(shí)器的向量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));// 啟動(dòng)定時(shí)器并等待它們到期for (auto &timer : timers) {std::thread t(std::ref(timer));t.detach(); // 將定時(shí)器線程分離,使其在后臺(tái)運(yùn)行}std::this_thread::sleep_for(std::chrono::seconds(10)); // 等待10秒鐘,使所有定時(shí)器都有足夠的時(shí)間到期return 0;
}
關(guān)于代碼中的void operator()()
Timer timer(i, interval);
這一行實(shí)際上是在創(chuàng)建 Timer
對(duì)象,并且在這個(gè)過程中沒有直接使用了 operator()()
函數(shù)調(diào)用運(yùn)算符。
operator()()
函數(shù)調(diào)用運(yùn)算符的使用方式是通過將 Timer
對(duì)象傳遞給 std::thread
的構(gòu)造函數(shù)來實(shí)現(xiàn)的,如下所示:
std::thread t(std::ref(timer));
這里的 timer
是一個(gè) Timer
類型的對(duì)象。通過傳遞 std::ref(timer)
給 std::thread
構(gòu)造函數(shù),你實(shí)際上在創(chuàng)建一個(gè)新的線程,并在這個(gè)新線程中調(diào)用了 timer
對(duì)象的 operator()()
函數(shù)。這就是代碼中使用 operator()()
函數(shù)的地方。