需求:

实现异步定时器,不干扰其它线程

实现:

使用select作为超时API,但一定程度增加系统payload

代码:

select_timer.hpp

#ifndef SRC_SELECT_TIMER_HPP_
#define SRC_SELECT_TIMER_HPP_
#include <sys/time.h>
#include <iostream>
#include <functional>
#include <thread>
using namespace std;
class select_timer {
public:
select_timer(function<void()>task, int seconds) {
thd_ = thread([this, &task, seconds] {
while (true) {
task();
do_select_timeout(seconds);
}
});
}
~select_timer() {
thd_.detach();
}
private:
void do_select_timeout(unsigned int seconds) {
struct timeval tv = {0};
tv.tv_sec = seconds;
int err = 0;
do {
err = select(0, nullptr, nullptr, nullptr, &tv);
}while (err < 0 && EINTR == errno);
}
private:
thread thd_;
};




#endif /* SRC_SELECT_TIMER_HPP_ */

main.cpp

#include "select_timer.hpp"
#include <iostream>
#include <chrono>
void fun() {
cout << "I am fun()." << endl;
}
void fun1() {
while (true) {
cout << "I am fun1." << endl;
this_thread::sleep_for(chrono::seconds(1));
}
}
int main() {
auto f = fun;
select_timer(f, 1);
thread th(fun1);
if (th.joinable()) {
th.join();
}

return 0;
}

make.sh

g++ -std=c++17 -g -o Test main.cpp  select_timer.hpp -pthread