BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Boost.Asio - 1. Blocking and non-blocking wait with timers - 2020





Bookmark and Share





bogotobogo.com site search:




Boost Installation



Boost on Ubuntu

We need to install boost library on Ubuntu:

$ $ cat /proc/version
Linux version 3.11.0-12-generic (buildd@allspice) (gcc version 4.8.1 (Ubuntu/Linaro 4.8.1-10ubuntu7) ) #19-Ubuntu SMP Wed Oct 9 16:20:46 UTC 2013

$ sudo apt-get install libboost-all-dev

Here is the list of installed boost libraries:

libboost_atomic
libboost_chrono
libboost_context
libboost_date_time
libboost_filesystem
libboost_graph_parallel
libboost_graph
libboost_iostreams
libboost_locale
libboost_math_c99f
libboost_math_c99l
libboost_math_c99
libboost_math_tr1f
libboost_math_tr1l
libboost_math_tr1
libboost_mpi_python-py27
libboost_mpi_python-py33
libboost_mpi_python
libboost_mpi
libboost_prg_exec_monitor
libboost_program_options
libboost_python-py27
libboost_python-py33
libboost_python
libboost_random
libboost_regex
libboost_serialization
libboost_signals
libboost_system
libboost_thread
libboost_timer
libboost_unit_test_framework
libboost_wave
libboost_wserialization







boost.asio : Blocking and Non-block wait()


Blocking wait on a timer (synchronous timer)

The timer is used in the following examples since it does not require any knowledge about network programming compared to the other I/O objects provided by asio.

The asio classes can be used by including the asio.hpp header file.

The following example will print out "Blocking wait()..." in 0, 1, 2, 3, and 4 second intervals by using a timer synchronously. That is, the call to wait() will not return until the timer has expired.

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

int main()
{
  boost::asio::io_service io;
 
  for(int i = 0; i < 5; i++) {
    boost::asio::deadline_timer timer(io, boost::posix_time::seconds(i));
    timer.wait();
    std::cout << "Blocking wait(): " << i << " second-wait\n";
  }

  return 0;
}

Here is the code: sync_timer.cpp.

Makefile looks like this:

sync_timer: sync_timer.o
        g++ -o sync_timer sync_timer.o -lboost_system -lboost_thread -lpthread
sync_timer.o: sync_timer.cpp
        g++ -c sync_timer.cpp
clean:
        rm -f *.o sync_timer

Output:

$ make
g++ -c sync_timer.cpp
g++ -o sync_timer sync_timer.o  -L /usr/lib -lboost_system -lboost_thread -lpthread

$ ./sync_timer
Blocking wait(): 0 second-wait
Blocking wait(): 1 second-wait
Blocking wait(): 2 second-wait
Blocking wait(): 3 second-wait
Blocking wait(): 4 second-wait
  1. To use timers, the Boost.Date_Time header file is included.
  2. We declared an io_service object io:
    boost::asio::io_service io;
    
  3. we declared an object of type boost::asio::deadline_timer.
  4. The asio classes that provide I/O (in this case timer) take a reference to an io_service as their first argument. The second argument sets the timer to expire in i seconds.
    boost::asio::deadline_timer t(io, boost::posix_time::seconds(i));
    
  5. We used a blocking wait on the timer. In other words, the call to deadline_timer::wait() will not return until the timer has expired.






Non-Blocking wait on a timer (asynchronous asynchronous wait on the timer)

The following code demonstrates how to use asio's asynchronous callback functionality and how to perform an asynchronous wait on the timer.

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

void work_for_io_service(const boost::system::error_code& /*e*/)
{
  std::cout << "Non-blocking wait() \n";
}

int main()
{
  boost::asio::io_service io;

  boost::asio::deadline_timer timer(io, boost::posix_time::seconds(5));

  // work_for_io_service() will be called 
  // when async operation (async_wait()) finishes  
  // note: Though the async_wait() immediately returns
  //       but the callback function will be called when time expires
  timer.async_wait(&work;_for_io_service);

  std::cout << " If we see this before the callback function, we know async_wait() returns immediately.\n This confirms async_wait() is non-blocking call!\n";

  // the callback function, work_for_io_service(), will be called 
  // from the thread where io.run() is running. 
  io.run();

  return 0;
}                           

Here is the code: async_timer.cpp.

When we use boost.asio for asynchronous data processing, we're relying on I/O services and I/O objects. While the I/O services abstract operating system interfaces that allow asynchronous data processing, the I/O objects are used to initiate certain operations such as boost::asio::io_service::run().

While it would be possible to call a function that returns after five seconds, an asynchronous operation is started with asio by calling the method async_wait() and passing the name of the handler function (work_for_io_service()) as its single argument.

Note that only the name of the handler function is passed but the function itself is not called.

The advantage of async_wait() is that the function call returns immediately instead of waiting five seconds. Once the time expires, the function provided as the argument is called accordingly. The application thus can execute other operations after calling async_wait() instead of just blocking.

That's why we call async_wait() non-blocking compared to the blocking wait() we used in the previous section where the execution flow should be blocked until a certain operation has finished.

While looking at the source code of the above example, it can be noticed that after the call to async_wait(), a method named run() is called on the I/O service. This is mandatory since control needs to be taken over by the operating system in order to call the callback handler function after five seconds.

The asio library provides a guarantee that callback handlers will only be called from threads that are currently calling io_service::run(). Therefore unless the io_service::run() function is called the callback for the asynchronous wait completion will never be invoked.

The io_service::run() function will also continue to run while there is still "work" to do. In this example, the work is the asynchronous wait on the timer, so the call will not return until the timer has expired and the callback has completed.

While async_wait() starts an asynchronous operation and returns immediately, run() actually blocks. Execution therefore stops at the call of run(). However, many operating systems support asynchronous operations via a blocking function only. The following example demonstrates why this limitations is typically not an issue.







On Blocking run() call

As discussed at the end of the last section, while the async_wait() starts an asynchronous operation and returns immediately, run() actually blocks. Therefore, the execution stops at the call of run().

The example below is using two I/O objects of type boost::asio::deadline_timer. The first I/O object expires after five seconds while the second one after ten seconds. After each period has elapsed, the functions work_for_io_service() and work_for_io_service_10() will be called.

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

void work_for_io_service(const boost::system::error_code& /*e*/)
{
  std::cout << "Non-blocking wait() 5 sec \n";
}

void work_for_io_service_10(const boost::system::error_code& /*e*/)
{
  std::cout << "Non-blocking wait() 10 sec \n";
}


int main()
{
  boost::asio::io_service io;

  boost::asio::deadline_timer timer(io, boost::posix_time::seconds(5));
  boost::asio::deadline_timer timer_10(io, boost::posix_time::seconds(10));

  timer.async_wait(&work;_for_io_service);
  timer_10.async_wait(&work;_for_io_service_10);

  io.run();

  return 0;
}

Here is the code: async_timer2.cpp.

Output:

$ ./async_timer2
Non-blocking wait() 5 sec 
Non-blocking wait() 10 sec 

As previously mentioned, the run() function practically blocks execution, and passing the control to the OS which takes over the asynchronous processing. With the aid of the OS, the two callback functions are called after 5 seconds and 10 seconds, respectively.

It may seem strange that asynchronous processing requires calling the blocking run() method. However, since the application needs to be prevented from terminating, this does actually not pose any issue. If the run() would not block, main() would actually finish prematurely and thus terminate the application. If execution of the application should not be blocked, run() should be called within a new thread since it naturally blocks the current thread only.

Once all asynchronous operations of the particular I/O service have been completed, controls is returned back to the run() method which simply returns the application terminates once all the timers expire.








Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






C++ Tutorials

C++ Home

Algorithms & 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

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






C++ Tutorials

C++ Home

Algorithms & 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...








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master