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

Boost C++ Application Development Cookbook - Second Edition

Antony Polukhin

Condividi libro
  1. 438 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Boost C++ Application Development Cookbook - Second Edition

Antony Polukhin

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul 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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Boost C++ Application Development Cookbook - Second Edition è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Boost C++ Application Development Cookbook - Second Edition di Antony Polukhin in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in C++. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2017
ISBN
9781787284838
Edizione
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...

Indice dei contenuti