boost::asio库源码分析之io_service实现(一)

1 io_service的实质

io_service实质是io_context的别名,文件在asio/io_service.hpp

//
// io_service.hpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_ASIO_IO_SERVICE_HPP
#define BOOST_ASIO_IO_SERVICE_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/io_context.hpp>

#include <boost/asio/detail/push_options.hpp>

namespace boost {
namespace asio {

#if !defined(BOOST_ASIO_NO_DEPRECATED)
/// Typedef for backwards compatibility.
typedef io_context io_service;
#endif // !defined(BOOST_ASIO_NO_DEPRECATED)

} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_IO_SERVICE_HPP

但是io_context也不是真正的实现类,io_context也是靠其他类(impl_type)实现的

io_context::io_context()
  : impl_(add_impl(new impl_type(*this, BOOST_ASIO_CONCURRENCY_HINT_DEFAULT)))
{
}

io_context::io_context(int concurrency_hint)
  : impl_(add_impl(new impl_type(*this, concurrency_hint == 1
          ? BOOST_ASIO_CONCURRENCY_HINT_1 : concurrency_hint)))
{
}

io_context::impl_type& io_context::add_impl(io_context::impl_type* impl)
{
  boost::asio::detail::scoped_ptr<impl_type> scoped_impl(impl);
  boost::asio::add_service<impl_type>(*this, scoped_impl.get());
  return *scoped_impl.release();
}

io_context::~io_context()
{
}

io_context::count_type io_context::run()
{
  boost::system::error_code ec;
  count_type s = impl_.run(ec);
  boost::asio::detail::throw_error(ec);
  return s;
} 

那impl_type是什么呢?在文件asio/io_context.hpp

class io_context
  : public execution_context
{
private:
  typedef detail::io_context_impl impl_type;
#if defined(BOOST_ASIO_HAS_IOCP)
  friend class detail::win_iocp_overlapped_ptr;
#endif

public:

可以看到impl_type实质为detail::io_context_impl,实现在文件asio/io_context.hpp

namespace boost {
namespace asio {

namespace detail {
#if defined(BOOST_ASIO_HAS_IOCP)
  typedef class win_iocp_io_context io_context_impl;
  class win_iocp_overlapped_ptr;
#else
  typedef class scheduler io_context_impl;
#endif
} // namespace detail

可以看到在非windows下为class scheduler,实现在文件asio/detail/scheduler.hpp和文件asio/detail/scheduler.ipp




猜你喜欢

转载自blog.csdn.net/idwtwt/article/details/80617322