boost之定时器和io_service

1.定时器的使用,sleep是等待线程,asio封装了操作系统的异步系统调用select,epoll.

io_servie 实现了一个任务队列,这里的任务就是void(void)的函数。Io_servie最常用的两个接口是post和run,post向任务队列中投递任务,run是执行队列中的任务,直到全部执行完毕,并且run可以被N个线程调用。Io_service是完全线程安全的队列。

#include <iostream>
#include <string>
#include <vector>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;
using namespace boost::asio;
using namespace boost;

int main()
{
	io_service ios;
	deadline_timer t(ios,posix_time::seconds(2));
	cout << t.expires_at() <<endl;
	t.wait();
	cout << "hello asio" <<endl;
	return 0;
	
}

 2.定时器的作用是类似sendto,recvfrom等IO操作,相当于等待一段时间有数据到达,而io_service的作用类似select,服务于IO。

异步I/O调用

#include <iostream>
#include <string>
#include <vector>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;
using namespace boost::asio;
using namespace boost;

void print(const system::error_code&)
{
	cout << "hello asio" <<endl;
}
int main()
{
	io_service ios;
	deadline_timer t(ios,posix_time::seconds(2));
	t.async_wait(print);
	cout << "it show before t exired" <<endl;
	ios.run();
	return 0;
	
}

 

posted @ 2013-08-13 23:37  l851654152  阅读(3608)  评论(0编辑  收藏  举报