您的位置:首页 > 其它

boost::asio-start(1): The basics of io_service详解

2014-09-18 10:28 561 查看
转自:http://www.gamedev.net/blog/950/entry-2249317-a-guide-to-getting-started-with-boostasio/?pg=2

我自己先学习了此文章,然后跟踪代码,了解了代码背后的操作。

Example - 1a

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

int main( int argc, char * argv[] )
{
	boost::asio::io_service io_service;

	io_service.run();

	std::cout << "Do you reckon this line displays?" << std::endl;

	return 0;
}
主要介绍了run的用法,当run时,如果此时没有pending的工作,io_service会立即返回。

看源码,如下:

size_t win_iocp_io_service::run(boost::system::error_code& ec)
{
  if (::InterlockedExchangeAdd(&outstanding_work_, 0) == 0)
  {
    stop();
    ec = boost::system::error_code();
    return 0;
  }

  win_iocp_thread_info this_thread;
  thread_call_stack::context ctx(this, this_thread);

  size_t n = 0;
  while (do_one(true, ec))
    if (n != (std::numeric_limits<size_t>::max)())
      ++n;
  return n;
}
其中
outstanding_work_
在构造的时候为0,构造io_service之后直接run的话,
InterlockedExchangeAdd
会返回1的,因此直接结束。

Example1b

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

int main( int argc, char * argv[] )
{
	boost::asio::io_service io_service;
	boost::asio::io_service::work work( io_service );

	io_service.run();

	std::cout << "Do you reckon this line displays?" << std::endl;

	return 0;
}
io_service::work会使io_service的outstanding_work_自加1,因此io_service再run的时候就,即使没有未执行的task也不立即返回。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: