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

Boost C++ Application Development Cookbook - Second Edition

Antony Polukhin

Partager le livre
  1. 438 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Boost C++ Application Development Cookbook - Second Edition

Antony Polukhin

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

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.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Boost C++ Application Development Cookbook - Second Edition est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Boost C++ Application Development Cookbook - Second Edition par Antony Polukhin en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Computer Science et Programming in C++. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2017
ISBN
9781787284838
Édition
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...

Table des matiĂšres