Timer.5 - Synchronising handlers in multithreaded programs
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的更多相关文章
- 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 ...
- boost::asio译文
Christopher Kohlhoff Copyright © 2003-2012 Christopher M. Kohlhoff 以Boost1.0的软件授权进行发布(见附带的LICENS ...
- Boost.Asio技术文档
Christopher Kohlhoff Copyright © 2003-2012 Christopher M. Kohlhoff 以Boost1.0的软件授权进行发布(见附带的LICENSE_1_ ...
- 【转】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 ...
- 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 ...
- Java性能提示(全)
http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLi ...
- Modules you should know in Python Libray
前两天被问到常用的python lib和module有哪些?最常用的那几个,其他的一下子竟然回答不上.想想也是,一般情况下,遇到一个问题,在网上一搜,顺着线索找到可用的例子,然后基本没有怎么深究.结果 ...
- Google C++ Style Guide
Background C++ is one of the main development languages used by many of Google's open-source project ...
- Programming with gtkmm 3
https://developer.gnome.org/gtkmm-tutorial/unstable/index.html.zh_CN 1. 序言 1.1. 本书 1.2. gtkmm 2. 安 ...
随机推荐
- FileZilla简单介绍及运用
一.FileZilla简介 FileZilla是一款免费开源的FTP客户端软件,并且还提供了服务器版本.虽然它是免费软件,可性能却一点也不含糊,比起那些共享软件来有过之而无不及,具备大多数的FTP软件 ...
- ant学习(1)
路径:/home/framework_Study/springinAction/webRoot/WEB-INF <?xml version="1.0" encoding=&q ...
- Web Api 跨域解决方案
一.跨域问题的由来 同源策略:出于安全考虑,浏览器会限制脚本中发起的跨站请求,浏览器要求JavaScript或Cookie只能访问同域下的内容. 正是由于这个原因,我们不同项目之间的调用就会被浏览器阻 ...
- ORACLE触发器概述之【语句触发器】【weber出品】
一.触发器概述 与表,视图,模式,或者数据库相关的PL/SQL过程,当触发条件被触发时,自动执行 分类: 1.语句触发器 2.行触发器 二.语句触发器 1. 什么是语句触发器 语句触发器,是指当执行D ...
- silverlight 生产图表(动态图表类型,Y轴数量) .xaml.cs文件
silverlight 页面后台方法 .xaml.cs文件 public void CreateChart(Grid oGrid, ObservableCollection<ListItem&g ...
- Web C# 导出Excel 方法总结
方法1:微软推荐服务器需安装Excel型 依赖: 软件:Office Excel 2007-2013 引用:Microsoft Office 14.0 Object Library 1.1 数据准备 ...
- DataSource
数据库连接池原理:在内存中开辟一段存储空间用来存储多个Connection连接,避免频繁的创建Connection,从而提高效率.代码如下: package jcbc.ds.test1; import ...
- CSS注意事项
1.定义样式不能就加:隔开 当有定义的css样式并没有起作用的时候看看定义该样式前边有没有加“;”的如 p{};div{}
- Hibernate配置文件中映射元素详解
对象标识符号 在关系数据库表中,主键(Primary Key)用来识别记录,并保证每条记录的唯一性.在Java语言中,通过比较两个变量所引用对象的内存地址是否相同,或者比较两个变量引用的对象值是否相同 ...
- Python基础第五天
双层装饰器 字符串格式化 Python字符串格式有2种方式:百分号方式.format方式:建议使用format方式 1.百分号方式 格式:%[(name)][flags][width].[precis ...