boost asio serial port

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;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值