使用select实现异步定时器

需求:

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

实现:

使用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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值