http://hi.baidu.com/jrckkyy/blog/item/7f3067395d8245f93b87ce15.html
// SuperCom.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <string>
//block timer
void TestTimer()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(3));
t.wait();
std::cout << "print out "<< std::endl;
}
void print(const boost::system::error_code & /*e*/)
{
std::cout <<"print out with asyn timeout" << std::endl;
}
void TestAsynTimer()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(4));
t.async_wait(print);
io.run();
}
void TestSerialPort()
{
using namespace boost::asio;
const char * com1 = "COM1";
io_service io;
serial_port sp(io, com1);
//1. setting com
sp.set_option(serial_port::baud_rate(9600));
sp.set_option(serial_port::parity(serial_port::parity::none));
sp.set_option(serial_port::stop_bits(serial_port::stop_bits::one));
sp.set_option(serial_port::character_size(8));
sp.set_option(serial_port::flow_control(serial_port::flow_control::none));
//3. write
char buf[100] = "strings";
size_t sz = sp.write_some(buffer(buf, 7));
sp.close();
}
using namespace boost::asio;
class Printer
{
public:
Printer(io_service &io, int i):m_io(io), m_int(i),m_timer(io)
{
std::cout << "start the printer" << std::endl;
m_timer.expires_from_now(boost::posix_time::seconds(1));
m_timer.async_wait(boost::bind(&Printer::print, this));
}
void print()
{
if(m_int > 10)
{
m_timer.cancel();
return;
}
std::cout << "print from mem function:" << m_int++ << ": end" << std::endl;
m_timer.expires_from_now(boost::posix_time::seconds(1));
m_timer.async_wait(boost::bind(&Printer::print, this));
}
private:
io_service &m_io;
int m_int;
deadline_timer m_timer;
};
void TestAsynTimer_memfn()
{
boost::asio::io_service io;
Printer p(io, 3);
io.run();
}
void CB()
{
char * buf = new char[1024*1024*10];
Sleep(2000);
std::cout << "alloc 10 M memory" << std::endl;
delete buf;
Sleep(2000);
std::cout << "free the 10 M memory" << std::endl;
}
#include <boost/thread.hpp>
//boost thread
void TestThreadMemory()
{
for(int i = 0; i < 100; ++i)
{
boost::thread t(CB);
t.join();
Sleep(2000);
std::cout << "alloc a thread & memory" << std::endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
//TestTimer();
//TestAsynTimer();
//TestSerialPort();
//TestAsynTimer_memfn();
//TestThreadMemory();
return 0;
}