Boost C++ Application Development Cookbook - Second Edition
eBook - ePub

Boost C++ Application Development Cookbook - Second Edition

Antony Polukhin

Compartir libro
  1. 438 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Boost C++ Application Development Cookbook - Second Edition

Antony Polukhin

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Learn to build applications faster and better by leveraging the real power of Boost and C++About This Book• Learn to use the Boost libraries to simplify your application development• Learn to develop high quality, fast and portable applications• Learn the relations between Boost and C++11/C++4/C++17Who This Book Is ForThis book is for developers looking to improve their knowledge of Boost and who would like to simplify their application development processes. Prior C++ knowledge and basic knowledge of the standard library is assumed.What You Will Learn• Get familiar with new data types for everyday use• Use smart pointers to manage resources• Get to grips with compile-time computations and assertions• Use Boost libraries for multithreading• Learn about parallel execution of different task• Perform common string-related tasks using Boost libraries• Split all the processes, computations, and interactions to tasks and process them independently• Learn the basics of working with graphs, stacktracing, testing and interprocess communications• Explore different helper macros used to detect compiler, platform and Boost featuresIn DetailIf you want to take advantage of the real power of Boost and C++ and avoid the confusion about which library to use in which situation, then this book is for you. Beginning with the basics of Boost C++, you will move on to learn how the Boost libraries simplify application development. You will learn to convert data such as string to numbers, numbers to string, numbers to numbers and more. Managing resources will become a piece of cake. You'll see what kind of work can be done at compile time and what Boost containers can do. You will learn everything for the development of high quality fast and portable applications. Write a program once and then you can use it on Linux, Windows, MacOS, Android operating systems. From manipulating images to graphs, directories, timers, files, networking – everyone will find an interesting topic.Be sure that knowledge from this book won't get outdated, as more and more Boost libraries become part of the C++ Standard.Style and approachClear step-by-step recipes that will help you take advantage of the real power of Boost.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Boost C++ Application Development Cookbook - Second Edition un PDF/ePUB en línea?
Sí, puedes acceder a Boost C++ Application Development Cookbook - Second Edition de Antony Polukhin en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in C++. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2017
ISBN
9781787284838
Edición
2

Manipulating Tasks

In this chapter, we will cover:
  • Registering a task for an arbitrary data type processing
  • Making timers and processing timer events as tasks
  • Network communication as a task
  • Accepting incoming connections
  • Executing different tasks in parallel
  • Pipeline tasks processing
  • Making a nonblocking barrier
  • Storing an exception and making a task from it
  • Getting and processing system signals as tasks

Introduction

This chapter is all about tasks. We'll be calling the functional object a task because it is shorter and better reflects what it will do. The main idea of this chapter is that we can split all the processing, computations, and interactions to functors (tasks), and process each of those tasks almost independently. Moreover, we may not block on some slow operations such as receiving data from the socket or waiting for the time out, but instead provide a callback task and continue working with other tasks. Once the OS finishes, the slow operation, our callback is executed.
The best way to understand the example is to play with it by modifying, running, and extending it. The site, http://apolukhin.github.io/Boost-Cookbook/, has all the examples from this chapter, and you can even play with some of them online.

Before you start

This chapter requires at least a basic knowledge of the first, second, and fifth chapters. Basic knowledge on C++11 rvalue references and lambdas is required.

Registering a task for an arbitrary data type processing

First of all, let's take care of the class that holds all the tasks and provides methods for their execution. We were already doing something like this in the Chapter 5, Multithreading, Creating a work_queue class recipe, but some of the following problems were not addressed:
  • A work_queue class was only storing and returning tasks, but we also need to execute existing tasks.
  • A task may throw an exception. We need to catch and process exceptions if they leave the task boundaries.
  • A task may not notice a thread interruption. The next task on the same thread may get the interruption instead.
  • We need a way to stop the processing of the tasks.

Getting ready

This recipe requires linking with the boost_system and boost_thread libraries. A basic knowledge of Boost.Thread is also required.

How to do it...

In this recipe, we use boost::asio::io_service instead of work_queue from the previous chapter. There is a reason for doing this, and we'll see it in the following recipes.
  1. Let's start from the structure that wraps around a user task:
#include <boost/thread/thread.hpp>
#include <iostream>

namespace detail {

template <class T>
struct task_wrapped {
private:
T task_unwrapped_;

public:
explicit task_wrapped(const T& f)
: task_unwrapped_(f)
{}

void operator()() const {
// Resetting interruption.
try {
boost::this_thread::interruption_point();
} catch(const boost::thread_interrupted&){}

try {
// Executing task.
task_unwrapped_();
} catch (const std::exception& e) {
std::cerr<< "Exception: " << e.what() << '\n';
} catch (const boost::thread_interrupted&) {
std::cerr<< "Thread interrupted\n";
} catch (...) {
std::cerr<< "Unknown exception\n";
}
}
};

} // namespace detail
  1. For ease of use, we'll create a function that produces task_wrapped from the user's functor:
namespace detail {

template <class T>
task_wrapped<T> make_task_wrapped(const T& task_unwrapped) {
return task_wrapped<T>(task_unwrapped);
}

} // namespace detail
  1. Now, we are ready to write the tasks_processor class:
#include <boost/asio/io_service.hpp> 

class tasks_processor: private boost::noncopyable {
protected:
static boost::asio::io_service& get_ios() {
static boost::asio::io_service ios;
static boost::asio::io_service::work work(ios);

return ios;
}
  1. Let's add the push_task method:
public:
template <class T>
static void push_task(const T& task_unwrapped) {
get_ios().post(detail::make_task_wrapped(task_unwrapped));
}
  1. Let's finish this class by adding the member functions for starting and stopping a task's execution loop:
 static void start() {
get_ios().run();
}

static void stop() {
get_ios().stop();
}
}; // tasks_processor
Done! Now, it is time to test our class:
int func_test() {
static int counter = 0;
++ counter;
boost::this_thread::interruption_point();

switch (counter) {
case 3:
throw std::logic_error("Just checking");

case 10:
// Emulation of thread interruption.
// Caught inside task_wrapped and does not stop execution.
throw boost::thread_interrupted();

case 90:
// Stopping the tasks_processor.
tasks_processor::stop();
}

return counter;
}
The main function may look like this:
int main () {
for (std::size_t i = 0; i < 100; ++i) {
tasks_processor::push_task(&func_test);
}

// Processing was not started.
assert(func_test() == 1);

// We can also use lambda as a task.
// Counting 2 + 2 asynchronously.
int sum = 0;
tasks_processor::push_task(
[&sum]() { sum = 2 + 2; }
);

// Processing was not started.
assert(sum == 0);

// Does not throw, but blocks till
// one of the tasks it is owning
// calls tasks_processor::stop().
tasks_processor::start();
assert(func_test() == 91);
}

How it works...

The boost::asio::io_service variable can store and execute tasks posted to it. But we may not post a user's tasks to it directly, because they may receive an interruption address...

Índice