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

Boost C++ Application Development Cookbook - Second Edition

Antony Polukhin

Share book
  1. 438 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Boost C++ Application Development Cookbook - Second Edition

Antony Polukhin

Book details
Book preview
Table of contents
Citations

About This Book

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.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on ā€œCancel Subscriptionā€ - itā€™s as simple as that. After you cancel, your membership will stay active for the remainder of the time youā€™ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlegoā€™s features. The only differences are the price and subscription period: With the annual plan youā€™ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, weā€™ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Boost C++ Application Development Cookbook - Second Edition an online PDF/ePUB?
Yes, you can access Boost C++ Application Development Cookbook - Second Edition by Antony Polukhin in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in C++. We have over one million books available in our catalogue for you to explore.

Information

Year
2017
ISBN
9781787284838
Edition
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 of contents