欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++ boost asio 学习(一) 博客分类: C++ c++boostasio 

程序员文章站 2024-03-06 13:50:50
...
跟着 http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/tutorial.html 学习asio。


编译的时候需要加上 -lboost_system

同步定时器例子

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

using namespace std;

void tuttimer1()
{
	boost::asio::io_service io;

	// 等待5秒
	boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));

	t.wait();
}


int main() {
	tuttimer1();
	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!

	return 0;
}


异步定时器例子
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

// 定义回调函数,asio库要求回调函数只能有一个参数,且为 const boost::system::error_code & 类型
void print(const boost::system::error_code& /*e*/) {
	cout << "This is asynchronous timer!" << endl;
}

void tuttimer2()
{
	boost::asio::io_service io;
	boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));

	cout << "asynchronous timer start!" << endl;
	t.async_wait(&print); // 异步等待,传入回调函数,立即返回
	cout << "asynchronous timer processing!" << endl;

	io.run(); // 很重要!异步IO必须。如果不调用run(),
	          // 虽然操作被异步执行了,但没有一个等待它完成的机制,回调函数将得不到执行机会。
	cout << "asynchronous timer end!" << endl;
}

int main() {
	tuttimer2();
	return 0;
}

/*
运行结果:
asynchronous timer start!
asynchronous timer processing!
This is asynchronous timer!
asynchronous timer end!
*/


异步定时器使用bind
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>

void print1(const boost::system::error_code& /*e*/,
		boost::asio::deadline_timer* t, int* count)
{
	if (*count < 5)
	{
		cout << *count << "\n" << endl;
		++(*count);

		t->expires_at(t->expires_at() + boost::posix_time::seconds(1));

		t->async_wait(boost::bind(print1, boost::asio::placeholders::error, t, count));
	}

}

void tuttimer3()
{
	boost::asio::io_service io;
	int count = 0;
	boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));

	t.async_wait(boost::bind(print1, boost::asio::placeholders::error, &t, &count));

	io.run();

	cout << "Final count is " << count << "\n" << endl;
}

int main() {
	tuttimer3();
	return 0;
}
/*
运行结果:
0

1

2

3

4

Final count is 5
*/
相关标签: c++ boost asio