1. 程式人生 > >boost::asio阻塞等待與非同步等待

boost::asio阻塞等待與非同步等待

阻塞等待:這裡會等待3秒然後才進行輸出。

#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

int main(void)
{
	boost::asio::io_service io;
	boost::asio::deadline_timer timer(io, boost::posix_time::seconds(3));
	timer.wait();
	std::cout << "this is blocking wait" << std::endl;

	system("pause");
	return 0;
}

非同步等待:需要一個回撥函式,在等待這個print回撥函式的時候程式會繼續往下執行到io.run為止,3秒過後才會執行回撥函式。如果在3秒內程式還沒有執行到io.run(如加上sleep(5)),那麼5秒後才會執行print,也就是說在執行io.run之前print是不會執行的。
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

void print(const boost::system::error_code & e)
{
	std::cout << "hello, world" << std::endl;
}

int main(void)
{
	boost::asio::io_service io;
	boost::asio::deadline_timer timer(io, boost::posix_time::seconds(3));
	timer.async_wait(&print);
	std::cout << "this is asynchronous wait" << std::endl;
        // sleep(5);
	io.run();

	system("pause");
	return 0;
}

// 開始timer的非同步等待時間是1秒,1秒後會執行print回撥函式,在這個函式裡會進行5次遞迴呼叫。由於timer的 // 終止時間是1秒已經到期了所以在遞迴的過程中不會再每秒執行一次的,為了實現每秒輸出的效果我們需要為這個 // timer延遲終止時間,expires_at就是其這個作用。當然expires_at必須在async_wait之前執行,否則是沒有效果的。
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>
#include <windows.h>

unsigned int start_t, end_t;
void print(const boost::system::error_code& e, boost::asio::deadline_timer* timer, int* count)
{
	if (*count < 5)
	{
		std::cout << "count: " << *count << std::endl;
		end_t = ::GetTickCount();
		std::cout << "elapse time:" << end_t-start_t << std::endl;
		++(*count);
                //timer->expires_from_now(boost::posix_time::seconds(1));
		timer->expires_at(timer->expires_at() + boost::posix_time::seconds(1));
		timer->async_wait(boost::bind(print, boost::asio::placeholders::error, timer, count));
	}
}

int main()
{
	int count = 0;
	boost::asio::io_service io;
	boost::asio::deadline_timer timer(io, boost::posix_time::seconds(1));
	timer.async_wait(boost::bind(print, boost::asio::placeholders::error, &timer, &count));
	start_t = ::GetTickCount();
	io.run();
	std::cout << "run end" << std::endl;

	system("pause");
	return 0;
}

// 下面是類成員函式回撥的形式
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>

class Printer
{
public:
	Printer(boost::asio::io_service& io)
		: count_(0), timer_(io, boost::posix_time::seconds(1))
	{
		timer_.async_wait(boost::bind(&Printer::print, this));
	}

	~Printer()
	{
	}

	void print()
	{
		if (count_ < 5)
		{
			std::cout << "count: " << count_ << std::endl;
			++count_;
			timer_.expires_from_now(boost::posix_time::seconds(1));
			timer_.async_wait(boost::bind(&Printer::print, this));
		}
	}

private:
	int count_;
	boost::asio::deadline_timer timer_;
};

int main()
{
	boost::asio::io_service io;
	Printer printer(io);
	io.run();

	system("pause");
	return 0;
}