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

Boost C++ Application Development Cookbook - Second Edition

Antony Polukhin

Buch teilen
  1. 438 Seiten
  2. English
  3. ePUB (handyfreundlich)
  4. Über iOS und Android verfügbar
eBook - ePub

Boost C++ Application Development Cookbook - Second Edition

Antony Polukhin

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

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.

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Boost C++ Application Development Cookbook - Second Edition als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu Boost C++ Application Development Cookbook - Second Edition von Antony Polukhin im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Computer Science & Programming in C++. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Jahr
2017
ISBN
9781787284838

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

Inhaltsverzeichnis