boost库应用(二)

两个简单例子,一个是线程,一个是定时器。

class exp_thread
{
public:
	exp_thread()
		:m_nData(0)
	{
		m_ptr_auto_thread = boost::make_shared<boost::thread>(boost::bind(&exp_thread::singlethread, this));
	}
	void singlethread()
	{
		while (m_nData < 5)
		{
			cout << m_nData++ << endl;
		}
	}
private:
	thread_ptr m_ptr_auto_thread;
	int m_nData;
};



int _tmain(int argc, _TCHAR* argv[])
{
	exp_thread obj;


	return 0;
}


#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/chrono.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/ref.hpp>
using namespace std;
class TimeTest;
typedef boost::shared_ptr<TimeTest>  ptr_auto_test;
typedef boost::shared_ptr<boost::asio::steady_timer>  ptr_auto_time;

class TimeTest
	:public boost::enable_shared_from_this<TimeTest>
{
public:
	TimeTest()
		:m_nData(0)
	{
		io_server_.reset();
		ptr_time = boost::make_shared<boost::asio::steady_timer>(boost::ref(io_server_));
	}
	~TimeTest()
	{

	}
	void Start()
	{
		ptr_time->expires_from_now(boost::chrono::seconds(1));
		ptr_time->async_wait(boost::bind(&TimeTest::running, shared_from_this()));
		io_server_.run();
	}
	void running()
	{
		printf("Data : %d\n", m_nData++);
		Start();
	}
private:
	ptr_auto_time ptr_time;
	int m_nData;
	boost::asio::io_service io_server_;
};


int _tmain(int argc, _TCHAR* argv[])
{
	
	ptr_auto_test  ptr_test;
	ptr_test = boost::make_shared<TimeTest>();
	ptr_test->Start();


	getchar();
	

	return 0;
}

比较简单的应用,还未到饮水思源的水平,只能先喝水!
 

你可能感兴趣的:(boost库应用(二))