C++ Reactive Programming
eBook - ePub

C++ Reactive Programming

Design concurrent and asynchronous applications using the RxCpp library and Modern C++17

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

C++ Reactive Programming

Design concurrent and asynchronous applications using the RxCpp library and Modern C++17

About this book

Learn how to implement the reactive programming paradigm with C++ and build asynchronous and concurrent applications

Key Features

  • Efficiently exploit concurrency and parallelism in your programs
  • Use the Functional Reactive programming model to structure programs
  • Understand reactive GUI programming to make your own applications using Qt

Book Description

Reactive programming is an effective way to build highly responsive applications with an easy-to-maintain code base. This book covers the essential functional reactive concepts that will help you build highly concurrent, event-driven, and asynchronous applications in a simpler and less error-prone way.

C++ Reactive Programming begins with a discussion on how event processing was undertaken by different programming systems earlier. After a brisk introduction to modern C++ (C++17), you'll be taken through language-level concurrency and the lock-free programming model to set the stage for our foray into the Functional Programming model. Following this, you'll be introduced to RxCpp and its programming model. You'll be able to gain deep insights into the RxCpp library, which facilitates reactive programming. You'll learn how to deal with reactive programming using Qt/C++ (for the desktop) and C++ microservices for the Web.

By the end of the book, you will be well versed with advanced reactive programming concepts in modern C++ (C++17).

What you will learn

  • Understand language-level concurrency in C++
  • Explore advanced C++ programming for the FRP
  • Uncover the RxCpp library and its programming model
  • Mix the FP and OOP constructs in C++ 17 to write well-structured programs
  • Master reactive microservices in C++
  • Create custom operators for RxCpp
  • Learn advanced stream processing and error handling

Who this book is for

If you're a C++ developer interested in using reactive programming to build asynchronous and concurrent applications, you'll find this book extremely useful. This book doesn't assume any previous knowledge of reactive programming.

Tools to learn more effectively

Saving Books

Saving Books

Keyword Search

Keyword Search

Annotating Text

Annotating Text

Listen to it instead

Listen to it instead

Information

Year
2018
Print ISBN
9781788629775
eBook ISBN
9781788624244
Edition
1

A Tour of Modern C++ and its Key Idioms

The classic C++ programming language was standardized in 1998 and it was followed by a small revision (mostly corrections) in 2003. To support advanced abstractions, developers relied on the Boost (http://www.boost.org) library and other public domain libraries. Thanks to the next wave of standardization, the language (from C++ 11 onward) was enhanced, and now developers can encode most widely used abstractions (supported by other languages) without relying on external libraries. Even threads and file-system interfaces, which came squarely under the aegis of libraries, are now part of the standard language. Modern C++ (which stands for C++ versions 11/14/17 ) contains superb additions to the language and its libraries, that make C++ the de-facto choice for writing industrial strength production software. The features covered in this chapter are the minimum set of features that a programmer has to understand to work with Reactive Programming constructs in general and RxCpp in particular. The primary objective of this chapter is to cover the most important additions to the language which makes implementing Reactive Programming constructs easier without resorting to esoteric language techniques. Constructs such as Lambda functions, automatic type inference, rvalue references, move semantics, and language level concurrency are some of the constructs which the authors of this book feel that every C++ programmer should know. In this chapter, we will cover the following topics:
  • Key concerns for C++ programming language design
  • Some enhancements to C++ for writing better code
  • Better memory management through rvalue references and move semantics
  • Better object lifetime management using an enhanced set of smart pointers
  • Behavioral parameterization using Lambda functions and expressions
  • Function Wrappers (the std::function type)
  • Miscellaneous features
  • Writing Iterators and Observers (to put everything together)

The key concerns of the C++ programming language

As far as developers are concerned, the three key concerns that C++ programming language designers keep in mind were (and still are) as follows:
  • Zero Cost Abstraction - No performance penalty for higher level abstraction
  • Expressivity - A user defined type (UDT) or class should be as expressive as built-in types
  • Substitutability - A UDT can be substituted wherever built-in-types are expected (as in generic data structures and algorithms)
We will discuss these briefly.

Zero cost abstraction

The C++ programming language has always helped developers to write code that exploits the microprocessor (on which generated code runs) and also raise the level of abstraction when it matters. While raising the abstraction, the designers of the language have always tried to minimize (almost eliminate) their performance overhead. This is called Zero Cost Abstraction or Zero Overhead Cost Abstraction. The only notable penalty you pay is the cost of indirect calls (through function pointers) while dispatching virtual functions. Despite adding tons of features to the language, the designers have maintained the "Zero Cost Abstraction" guarantee implied by the language from its inception.

Expressivity

C++ helps a developer to write user defined types or classes that can be as expressive as the built-in types of the programming languages. This enables one to write a arbitrary-precision arithmetic class (monikered as BigInteger/BigFloat in some languages), which contains all the features of a double or float. For the sake of explanation, we have defined a SmartFloat class that wraps IEEE double precision floating point numbers and most of the operators available to the double data type is overloaded. The following code snippets show that one can write types that mimic the semantics of built-in types such as int, float, or double:
//---- SmartFloat.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class SmartFloat {
double _value; // underlying store
public:
SmartFloat(double value) : _value(value) {}
SmartFloat() : _value(0) {}
SmartFloat( const SmartFloat& other ) { _value = other._value; }
SmartFloat& operator = ( const SmartFloat& other ) {
if ( this != &other ) { _value = other._value;}
return *this;
}
SmartFloat& operator = (double value )
{ _value = value; return *this;}
~SmartFloat(){ }
The SmartFloat class wraps a double value and has defined some constructors and assignment operators to initialize instances properly. In the following snippet, we will define some operators that help to increment the value. Both the prefix and postfix variants of operators are defined:
 SmartFloat& operator ++ () { _value++; return *this; }
SmartFloat operator ++ (int) { // postfix operator
SmartFloat nu(*this); ++_value; return nu;
}
SmartFloat& operator -- () { _value--; return *this; }
SmartFloat operator -- (int) {
SmartFloat nu(*this); --_value; return nu;
}
The preceding code snippets implement increment operators (both prefix and postfix) and are meant for demonstration purposes only. In a real-world class, we will check for floating point overflow and underflow to make the code more robust. The whole purpose of wrapping a type is to write robust code!
 SmartFloat& operator += ( double x ) { _value += x; return *this;}
SmartFloat& operator -= ( double x ) { _value -= x;return *this; }
SmartFloat& operator *= ( double x ) { _value *= x; return *this;}
SmartFloat& operator /= ( double x ) { _value /= x; return *this;}
The preceding code snippets implement C++ style assignment operators and once again, to make the listing short, we have not checked whether any floating point overflow or underflow is there. We do not handle exceptions as well here to keep the listing brief.
 bool operator > ( const SmartFloat& other )
{ return _value > other._value; }
bool operator < ( const SmartFloat& other )
{return _value < other._value;}
bool operator == ( const SmartFloat& other )
{ return _value == other._value;}
bool operator != ( const SmartFloat& other )
{ return _value != other._value;}
bool operator >= ( const SmartFloat& other )
{ return _value >= other._value;}
bool operator <= ( const SmartFloat& other )
{ return _value <= other._value;}
The preceding code implements relational operators and most of the semantics associated with double precision floating points have been implemented as shown:
 operator int () { return _value; }
operator double () { return _value;}
};
For the sake of completeness, we have implemented conversion operators to int and double. We will write two functions to aggregate values stored in an array. The first function expects an array of double as parameter and the second one expects a SmartFloat array as parameter. The code is identical in both routines and only the type changes. Both will produce the same result:
double Accumulate( double a[] , int count ){
double value = 0;
for( int i=0; i<count; ++i) { value += a[i]; }
return value;
}
double Accumulate( SmartFloat a[] , int count ){
SmartFloat value = 0;
for( int i=0; i<count; ++i) { value += a[i]; }
return value;
}
int main() {
// using C++ 1z's initializer list
double x[] = { 10.0,20.0,30,40 };
SmartFloat y[] = { 10,20.0,30,40 };
double res = Accumulate(x,4); // will call the double version
cout << res << endl;
res = Accumulate(y,4); // will call the SmartFloat version
cout << res << endl;
}
The C++ language helps us write expressive types that augment the semantics of basic types. The expressiveness of the language also helps one to write good value types and reference types using a myriad of techniques supported by the language. With support for operator overloading, conversion operators, placement new, and other related techniques, the language has taken the class design to a higher level compared to other languages of its time. But, with power comes responsibility and the language sometimes gives you enough rope to shoot yourself in the foot.

Substitutability

In the previous example, we saw how a user-defined type can be used to express all the operations done on a built-in type. Another goal of C++ is to write code in a generic manner where we can substitute a user-defined class that mimics the semantics of one of the built-in types such as float, double, int, and so on:
//------------- from SmartValue.cpp
template <class T>
T Accumulate( T a[] , int count ) {
T value = 0;
for( int i=0; i<count; ++i) { value += a[i]; }
return value;
}
int main(){
//----- Templated version of SmartFloat
SmartValue<double> y[] = { 10,20.0,30,40 };
double res = Accumulate(y,4);
cout << res << endl;
}
The C++ programming language s...

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Packt Upsell
  4. Contributors
  5. Preface
  6. Reactive Programming Model – Overview and History
  7. A Tour of Modern C++ and its Key Idioms
  8. Language-Level Concurrency and Parallelism in C++
  9. Asynchronous and Lock-Free Programming in C++
  10. Introduction to Observables
  11. Introduction to Event Stream Programming Using C++
  12. Introduction to Data Flow Computation and the RxCpp Library
  13. RxCpp – the Key Elements
  14. Reactive GUI Programming Using Qt/C++
  15. Creating Custom Operators in RxCpp
  16. Design Patterns and Idioms for C++ Rx Programming
  17. Reactive Microservices Using C++
  18. Advanced Streams and Handling Errors
  19. Other Books You May Enjoy

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn how to download books offline
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
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 990+ topics, we’ve got you covered! Learn about our mission
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 about Read Aloud
Yes! You can use the Perlego app on both iOS and Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app
Yes, you can access C++ Reactive Programming by Praseed Pai, Peter Abraham in PDF and/or ePUB format, as well as other popular books in Informatique & Programmation. We have over one million books available in our catalogue for you to explore.