Boost.Asio - 2. Binding arguments to a callback handler member function - 2020
To implement a repeating timer using asio, we need to change the timer's expiration in our callback function, and to then start a new asynchronous wait.
Actually, we want the timer fires once a second and this reqires passing additional parameters to our handler function.
Usually, the asynchronous wait function, timer.async_wait(&callback;_handler) takes one argument which is the function name. But we cannot pass parameters to the handler.
The example below shows how we can pass parameters, and use that parameters to control the expiration of the timer.
#include <iostream> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> void handler(const boost::system::error_code& /*e*/, boost::asio::deadline_timer* timer, int* count) { if (*count < 5) { std::cout << *count << "\n"; ++(*count); timer->expires_at(timer->expires_at() + boost::posix_time::seconds(1)); timer->async_wait( boost::bind(handler, boost::asio::placeholders::error, timer, count)); } } int main() { boost::asio::io_service io; int count = 0; boost::asio::deadline_timer timer(io, boost::posix_time::seconds(1)); timer.async_wait( boost::bind(handler, boost::asio::placeholders::error, &timer;, &count;)); io.run(); std::cout << "The last count : " << count << "\n"; return 0; }
Here is the code: timer_bind.cpp.
Output:
$ ./timer_bind 0 1 2 3 4 The last count : 5
To implement a repeating timer using asio, we need to control the timer's expiration time in our callback function, and to then start a new asynchronous wait, which means that the callback function will need to be able to access the timer object. So, we added two new parameters to the handler() function:
void handler(const boost::system::error_code& /*e*/, boost::asio::deadline_timer* timer, int* count)
- A pointer to a timer object.
- A counter so that we can stop the program when the timer fires for the 6th time.
Note that there is no explicit call to ask the io_service to stop even though we uses a counter to stop running when the timer fires for the sixth time. Remember that the io_service::run() function will returns when there is no more "work" to do. Therefore, by not starting a new asynchronous wait on the timer when count reaches 5, the io_service will have no more work to do and stop running.
The boost::bind() function is used to associate the extra parameters with our callback handler. The deadline_timer::async_wait() function expects a handler function (or function object) with the signature void(const boost::system::error_code&). Binding the additional parameters converts our handler() function into a function object that matches the signature correctly.
The boost::asio::placeholders::error argument of boost::bind() is a named placeholder for the error object passed to the handler. When initiating the asynchronous operation, and if using boost::bind(), we must specify only the arguments that match the handler's parameter list:
timer->async_wait( boost::bind(handler, boost::asio::placeholders::error, timer, count));
Note that a new count variable is added so that we can stop the program when the timer fires for the 6th time.
Instead of defining a free function handler() as the callback handler, as we did in the previous section, we now define a class called handler.
#include <iostream> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> class handler { public: handler(boost::asio::io_service& io) : m_timer(io, boost::posix_time::seconds(1)), m_count(0) { m_timer.async_wait(boost::bind(&handler;::message, this)); } ~handler() { std::cout << "The last count : " << m_count << "\n"; } void message() { if (m_count < 5) { std::cout << m_count << "\n"; ++m_count; m_timer.expires_at(m_timer.expires_at() + boost::posix_time::seconds(1)); m_timer.async_wait(boost::bind(&handler;::message, this)); } } private: boost::asio::deadline_timer m_timer; int m_count; }; int main() { boost::asio::io_service io; handler h(io); io.run(); return 0; }
Here is the code: handler.cpp.
The constructor of class handler will take a reference to the io_service object
handler(boost::asio::io_service& io) : m_timer(io, boost::posix_time::seconds(1)), m_count(0) { m_timer.async_wait(boost::bind(&handler;::message, this)); }
and use it when initialising the m_timer member. The counter is now also a member of the class (m_count).
The handler() member function is very similar to the handler() function from the previous section, except that it now operates on the class data members instead of having the timer and counter passed in as parameters.
C++ Tutorials
C++ HomeAlgorithms & Data Structures in C++ ...
Application (UI) - using Windows Forms (Visual Studio 2013/2012)
auto_ptr
Binary Tree Example Code
Blackjack with Qt
Boost - shared_ptr, weak_ptr, mpl, lambda, etc.
Boost.Asio (Socket Programming - Asynchronous TCP/IP)...
Classes and Structs
Constructor
C++11(C++0x): rvalue references, move constructor, and lambda, etc.
C++ API Testing
C++ Keywords - const, volatile, etc.
Debugging Crash & Memory Leak
Design Patterns in C++ ...
Dynamic Cast Operator
Eclipse CDT / JNI (Java Native Interface) / MinGW
Embedded Systems Programming I - Introduction
Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora
Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain
Exceptions
Friend Functions and Friend Classes
fstream: input & output
Function Overloading
Functors (Function Objects) I - Introduction
Functors (Function Objects) II - Converting function to functor
Functors (Function Objects) - General
Git and GitHub Express...
GTest (Google Unit Test) with Visual Studio 2012
Inheritance & Virtual Inheritance (multiple inheritance)
Libraries - Static, Shared (Dynamic)
Linked List Basics
Linked List Examples
make & CMake
make (gnu)
Memory Allocation
Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.
Multi-Threaded Programming II - Native Thread for Win32 (A)
Multi-Threaded Programming II - Native Thread for Win32 (B)
Multi-Threaded Programming II - Native Thread for Win32 (C)
Multi-Threaded Programming II - C++ Thread for Win32
Multi-Threaded Programming III - C/C++ Class Thread for Pthreads
MultiThreading/Parallel Programming - IPC
Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)
Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)
Multithread Debugging
Object Returning
Object Slicing and Virtual Table
OpenCV with C++
Operator Overloading I
Operator Overloading II - self assignment
Pass by Value vs. Pass by Reference
Pointers
Pointers II - void pointers & arrays
Pointers III - pointer to function & multi-dimensional arrays
Preprocessor - Macro
Private Inheritance
Python & C++ with SIP
(Pseudo)-random numbers in C++
References for Built-in Types
Socket - Server & Client
Socket - Server & Client 2
Socket - Server & Client 3
Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)
Stack Unwinding
Standard Template Library (STL) I - Vector & List
Standard Template Library (STL) II - Maps
Standard Template Library (STL) II - unordered_map
Standard Template Library (STL) II - Sets
Standard Template Library (STL) III - Iterators
Standard Template Library (STL) IV - Algorithms
Standard Template Library (STL) V - Function Objects
Static Variables and Static Class Members
String
String II - sstream etc.
Taste of Assembly
Templates
Template Specialization
Template Specialization - Traits
Template Implementation & Compiler (.h or .cpp?)
The this Pointer
Type Cast Operators
Upcasting and Downcasting
Virtual Destructor & boost::shared_ptr
Virtual Functions
Programming Questions and Solutions ↓
Strings and Arrays
Linked List
Recursion
Bit Manipulation
Small Programs (string, memory functions etc.)
Math & Probability
Multithreading
140 Questions by Google
Qt 5 EXPRESS...
Win32 DLL ...
Articles On C++
What's new in C++11...
C++11 Threads EXPRESS...
Go Tutorial
OpenCV...
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization