Book Image

Boost.Asio C++ Network Programming

By : Wisnu Anggoro
Book Image

Boost.Asio C++ Network Programming

By: Wisnu Anggoro

Overview of this book

Table of Contents (15 chapters)
Boost.Asio C++ Network Programming Second Edition
Credits
About the Authors
Acknowledgements
About the Reviewers
www.PacktPub.com
Preface
Index

Serializing the I/O service work


Suppose we want to queue up the work to be done but the order is important. If we just apply the asynchronous method, we won't know the order of work we will get. We need to make sure that the order of work is the one we want and have designed it to be. For instance, if we post Work A, Work B, and Work C, in that order, we want to keep that order at runtime.

Using the strand function

Strand is a class in the io_service object that provides handler execution serialization. It can be used to ensure the work we have will be executed serially. Let us examine the following code to understand serializing by using the strand function. But first, we will start without using the strand() and lock() functions:

/* nonstrand.cpp */
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
#include <iostream>

boost::mutex global_stream_lock;

void...