数 main() 首先定义了一个I/O 服务 io_service,用于初始化I/O 对象 timer。 就象
boost::asio::deadline_timer那样,所有 I/O 对象通常都需要一个 I/O 服务作为它们的构造函数的第一个参数。 由于timer 的作用类似于一个闹钟, 所以 boost::asio::deadline_timer 的构造函数可以传入第二个参数, 用于表示在某个时间点或是在某段时长之后闹钟停止。 以上例子指定了五秒的时长, 该闹钟在timer 被定义之后立即开始计时。虽然我们可以调用一个在五秒后返回的函数,但是通过调用方法async_wait()并传入 handler() 函数的名字作为唯一参数,可以让Asio 启动一个异步操作。 请留意,我们只是传入了 handler() 函数的名字,而该函数本身并没有被调用。
async_wait()的好处是,该函数调用会立即返回,而不是等待五秒钟。 一旦闹钟时间到,作为参数所提供的函数就会被相应调用。 因此,应用程序可以在调用了async_wait()之后执行其它操作,而不是阻塞在这里。象async_wait()这样的方法被称为是非阻塞式的。I/O 对象通常还提供了阻塞式的方法, 可以让执行流在特定操作完成之前保持阻塞。 例如,可以调用阻塞式的 wait() 方法,取代 boost::asio::deadline_timer 的调用。 由于它会阻塞调用,所以它不需要传入一个函数名,而是在指定时间点或指定时长之后返回
#include "boost/thread.hpp"
#include "boost/asio.hpp"
#include <iostream>
boost::mutex mutex;
void waits(int &s)
{
boost::this_thread::sleep(boost::posix_time::seconds(s));
}
void handle(const boost::system::error_code & ec)
{
std::cout<<"5S"<<std::endl;
}
void thread()
{
mutex.lock();
for (int i = 0; i < 5; ++i)
{
waits(i);
std::cout << i << std::endl;
}
mutex.unlock();
}
int _tmain(int argc, _TCHAR* argv[])
{
// boost::thread t(thread);
// boost::thread t1(thread);
boost::asio::io_service io_service;
boost::asio::deadline_timer timer(io_service, boost::posix_time::seconds(5));
timer.async_wait(handle);
io_service.run();
while(1);
return 0;
}
boost::asio::io_service io_service;
boost::asio::deadline_timer timer(io_service, boost::posix_time::seconds(5));
//timer.wait();
timer.async_wait(handle);
//io_service.run();
boost::asio::deadline_timer timer2(io_service, boost::posix_time::seconds(2));
timer2.async_wait(handle2);
io_service.run();
while(1);
return 0;