라이브러리 'muduo 간단한 타이머 프로그램

설명 : 채널에 결합 파일 기술자 timerfd, 채널 () 콜백 함수 시간 제한을 설정합니다. EventLoop 모니터 timerfd. 타이머가 시작됩니다. 타이머가 만료되면, timerfd 활성화됩니다, 다음 채널이 타임 아웃 ()를 호출합니다. 전체 과정은 같다.

#include <muduo/net/EventLoop.h>
#include <muduo/net/Channel.h>
#include <sys/timerfd.h>
#include <boost/bind.hpp>

muduo::net::EventLoop *g_loop;

void timeout(){
	printf("Timeout!\n");
	g_loop->quit();
}

int main()
{
	muduo::net::EventLoop loop;
	g_loop = &loop;
	
	int timerfd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); // CLOCK_MONOTONIC: 单调时间,表示系统启动后流逝的时间,由变量jiffies来记录的。
	muduo::net::Channel channel(&loop, timerfd); // channel绑定到timerfd上
	channel.setReadCallback(boost::bind(timeout)); // 此处必须用bind形式
	channel.enableReading(); // 此处必须开启
	
	struct itimerspec howlong;
	/*
	struct itimerspec 
	{
		struct timespec it_interval;  // Timer interval(timer循环时间间隔) 
		struct timespec it_value;     // Initial expiration(timer初次到期时间间隔) 
	};
	参考:https://www.cnblogs.com/LubinLew/p/POSIX-DataStructure.html
	*/
	bzero(&howlong, sizeof (howlong));
	howlong.it_value.tv_sec = 1; // 设置超时时间
	::timerfd_settime(timerfd, 0, &howlong, NULL); // 开始计时。超时就激活timerfd
	/*
	 int timerfd_settime(int fd, int flags, const struct itimerspec *new_value, struct itimerspec *old_value);
	 
	13 
	14     timerfd_settime()此函数用于设置新的超时时间,并开始计时,能够启动和停止定时器;
	15     fd: 参数fd是timerfd_create函数返回的文件句柄
	16     flags:参数flags为1代表设置的是绝对时间(TFD_TIMER_ABSTIME 表示绝对定时器);为0代表相对时间。
	17     new_value: 参数new_value指定定时器的超时时间以及超时间隔时间
	18     old_value: 如果old_value不为NULL, old_vlaue返回之前定时器设置的超时时间,具体参考timerfd_gettime()函数
	19     
	20     ** it_interval不为0则表示是周期性定时器。
	21        it_value和it_interval都为0表示停止定时器
	22 
	参考:https://www.cnblogs.com/wenqiang/p/6698371.html
	*/
	
	loop.loop();
	
	::close(timerfd);
	
    return 0;
}

참조 "리눅스 멀티 스레드 서버 측 프로그래밍."

게시 92 개 원래 기사 · 원 찬양 2 · 조회수 3406

추천

출처blog.csdn.net/zxc120389574/article/details/105257620