Boost Asio总结(7)class strand

strand 保证异步代码在多线程环境中正确执行,无须使用互斥量,好比一组handler的锁,加入线程保护,保证handler不会存在线程并发访问。

多个线程使用io_service需要strand保证线程安全。

class strand
{
    
    
//返回context
  execution_context& context() const BOOST_ASIO_NOEXCEPT
  {
    
    
    return executor_.context();
  }

//要求异步执行一个handler
  template <typename Function, typename Allocator>
  void dispatch(BOOST_ASIO_MOVE_ARG(Function) f, const Allocator& a) const
  {
    
    
    detail::strand_executor_service::dispatch(impl_,
        executor_, BOOST_ASIO_MOVE_CAST(Function)(f), a);
  }

//要求异步执行一个handler
  /// Request the strand to invoke the given function object. 
  template <typename Function, typename Allocator>
  void post(BOOST_ASIO_MOVE_ARG(Function) f, const Allocator& a) const
  {
    
    
    detail::strand_executor_service::post(impl_,
        executor_, BOOST_ASIO_MOVE_CAST(Function)(f), a);
  }


  bool running_in_this_thread() const BOOST_ASIO_NOEXCEPT
  {
    
    
    return detail::strand_executor_service::running_in_this_thread(impl_);
  }

猜你喜欢

转载自blog.csdn.net/thefist11cc/article/details/123563954