This tutorial demonstrates the use of the boost::asio::strand class to synchronise callback handlers in a multithreaded program.

The previous four tutorials avoided the issue of handler synchronisation by calling the boost::asio::io_service::run() function from one thread only. As you already know, the asio library provides a guarantee that callback handlers will only be called from threads that are currently calling boost::asio::io_service::run(). Consequently, calling boost::asio::io_service::run() from only one thread ensures that callback handlers cannot run concurrently.

The single threaded approach is usually the best place to start when developing applications using asio. The downside is the limitations it places on programs, particularly servers, including:

  • Poor responsiveness when handlers can take a long time to complete.
  • An inability to scale on multiprocessor systems.

If you find yourself running into these limitations, an alternative approach is to have a pool of threads calling boost::asio::io_service::run(). However, as this allows handlers to execute concurrently, we need a method of synchronisation when handlers might be accessing a shared, thread-unsafe resource.

#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

We start by defining a class called printer, similar to the class in the previous tutorial. This class will extend the previous tutorial by running two timers in parallel.

class printer
{
public:

In addition to initialising a pair of boost::asio::deadline_timer members, the constructor initialises the strand_ member, an object of type boost::asio::strand.

An boost::asio::strand guarantees that, for those handlers that are dispatched through it, an executing handler will be allowed to complete before the next one is started. This is guaranteed irrespective of the number of threads that are calling boost::asio::io_service::run(). Of course, the handlers may still execute concurrently with other handlers that were not dispatched through an boost::asio::strand, or were dispatched through a different boost::asio::strand object.

  printer(boost::asio::io_service& io)
: strand_(io),
timer1_(io, boost::posix_time::seconds(1)),
timer2_(io, boost::posix_time::seconds(1)),
count_(0)
{

When initiating the asynchronous operations, each callback handler is "wrapped" using the boost::asio::strand object. The boost::asio::strand::wrap() function returns a new handler that automatically dispatches its contained handler through the boost::asio::strand object. By wrapping the handlers using the same boost::asio::strand, we are ensuring that they cannot execute concurrently.

    timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
} ~printer()
{
std::cout << "Final count is " << count_ << "\n";
}

In a multithreaded program, the handlers for asynchronous operations should be synchronised if they access shared resources. In this tutorial, the shared resources used by the handlers (print1 and print2) are std::cout and the count_ data member.

  void print1()
{
if (count_ < 10)
{
std::cout << "Timer 1: " << count_ << "\n";
++count_; timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
}
} void print2()
{
if (count_ < 10)
{
std::cout << "Timer 2: " << count_ << "\n";
++count_; timer2_.expires_at(timer2_.expires_at() + boost::posix_time::seconds(1));
timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
}
} private:
boost::asio::strand strand_;
boost::asio::deadline_timer timer1_;
boost::asio::deadline_timer timer2_;
int count_;
};

The main function now causes boost::asio::io_service::run() to be called from two threads: the main thread and one additional thread. This is accomplished using an boost::thread object.

Just as it would with a call from a single thread, concurrent calls to boost::asio::io_service::run() will continue to execute while there is "work" left to do. The background thread will not exit until all asynchronous operations have completed.

int main()
{
boost::asio::io_service io;
printer p(io);
boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
io.run();
t.join(); return 0;
}

See the full source listing

Timer.5 - Synchronising handlers in multithreaded programs的更多相关文章

  1. Timer.4 - Using a member function as a handler

    In this tutorial we will see how to use a class member function as a callback handler. The program s ...

  2. boost::asio译文

        Christopher Kohlhoff Copyright © 2003-2012 Christopher M. Kohlhoff 以Boost1.0的软件授权进行发布(见附带的LICENS ...

  3. Boost.Asio技术文档

    Christopher Kohlhoff Copyright © 2003-2012 Christopher M. Kohlhoff 以Boost1.0的软件授权进行发布(见附带的LICENSE_1_ ...

  4. 【转】Multithreaded Python Tutorial with the “Threadworms” Demo

    The code for this tutorial can be downloaded here: threadworms.py or from GitHub. This code works wi ...

  5. Introduction to Multi-Threaded, Multi-Core and Parallel Programming concepts

    https://katyscode.wordpress.com/2013/05/17/introduction-to-multi-threaded-multi-core-and-parallel-pr ...

  6. Java性能提示(全)

    http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLi ...

  7. Modules you should know in Python Libray

    前两天被问到常用的python lib和module有哪些?最常用的那几个,其他的一下子竟然回答不上.想想也是,一般情况下,遇到一个问题,在网上一搜,顺着线索找到可用的例子,然后基本没有怎么深究.结果 ...

  8. Google C++ Style Guide

    Background C++ is one of the main development languages used by many of Google's open-source project ...

  9. Programming with gtkmm 3

      https://developer.gnome.org/gtkmm-tutorial/unstable/index.html.zh_CN 1. 序言 1.1. 本书 1.2. gtkmm 2. 安 ...

随机推荐

  1. sql 读取excel中的数据

    select 列名 as 字段名 from openBowSet('MSDASQL.1','driver=Microsoft Excel Driver(*.xls);dbq=文件存放地址','sele ...

  2. NPOI导入导出Excel

    .net mvc利用NPOI导入导出excel 注意:如何导出的提交方式ajax导出是失效的! 解决方案是:js处理l两个表单的提交  代码:  第一步. 在页面里面加入2个隐藏的iframe, 如下 ...

  3. 3 linux、windows环境---路径分隔符不同导致的问题

    问题:通常在eclipse,IntelliJ IDEA等进行代码编写时,程序中用到路径通常采用/job/test.properties或D:/job/test.properties等是形式作为文件路径 ...

  4. poj2385 简单DP

    J - 简单dp Crawling in process... Crawling failed Time Limit:1000MS     Memory Limit:65536KB     64bit ...

  5. IntelliJ IDEA14如何配置tomcat

    http://doc.okbase.net/frank1234/archive/121479.html

  6. struts.custom.i18n.resources国际化详解(一)

    每种框价都会有国际化的支持,struts2的国际化大致上分为页面的国际化,Action的国际化以及xml的国际化 首先在struts.properties文件中加入以下内容:struts.custom ...

  7. 继刚接触play framework后,一些心得

    我是个小菜鸟,我这些体会跟心得纯属个人观点,仅供参考,勿喷,我想记录下学习的历程,不断成长 在play2.0的框架里面  用到的最多的语言就是scala,对于习惯了java语言的我们来说  看这些语言 ...

  8. IE10-IE11在NET4.0下出现“__doPostBack未定义”解决方案

    IE10在NET4.0下出现"__doPostBack未定义"的办法 参考文章: http://blogs.msdn.com/b/scott_hanselman/archive/2 ...

  9. Log4net从下载到使用例子

    一.首先下载log4net.dll   http://pan.baidu.com/s/1gdigrwJ 二.添加log4net引用 三.代码: using System; using System.C ...

  10. wordpress显示多个分类的文章

    显示多个分类下的文章可以这样提取: <?php query_posts(array('posts_per_page'=>10,'orderby'=>'rand','category_ ...