40,81 €
Learn how to implement the reactive programming paradigm with C++ and build asynchronous and concurrent applications
Key Features
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
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.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 399
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Richa TripathiAcquisition Editor: Sandeep MishraContent Development Editor: Rohit SinghTechnical Editor: Ketan KambleCopy Editor: Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics: Jason MonteiroProduction Coordinator: Shraddha Falebhai
First published: June 2018
Production reference: 1280618
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78862-977-5
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Praseed Pai has been working in the software industry for the last 25 years, starting his career as a MS-DOS systems programmer using ANSI C. He has been actively involved in developing large-scale, cross-platform, native code-based systems using C++ on Windows, GNU Linux, and macOS X. He has experience in COM+ and CORBA programming using C++. In the last decade, he has worked with Java- and .NET-based systems.
He is the primary implementer of the SLANG4.net compilation system, which has been ported to C++ with an LLVM backend. He coauthored .NET Design Patterns, by Packt Publishing.
Peter Abraham has been a performance fanatic and a C/C++ programming language enthusiast right from his college days, where he excelled in Microsoft Windows programming and GNU Linux programming. He garnered experience in working with CUDA, image processing, and computer graphics programs by virtue of working with companies such as Quest Global, Siemens, and Tektronics.
Peter has been eagerly following the C++ standard and RxCpp libraries as part of his profession. He has worked with cross-platform GUI toolkits such as Qt, WxWidgets, and FOX toolkit.
Sumant Tambe is a software engineer, researcher, open source contributor, blogger, speaker, author, and gamer. He is experienced in using Modern C++, Kafka, data distribution service, reactive programming, and stream processing to solve new problems in big data and industrial IoT.
He has authored C++ Truths blog and the More C++ Idioms wikibook. He shares his learnings on his blog, and at local code camps, meetups, and conferences. He has been a recipient of the Microsoft MVP Award in development technologies for 5 years. He has a PhD in computer science from Vanderbilt University.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
C++ Reactive Programming
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the authors
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Reactive Programming Model – Overview and History
Event-driven programming model
Event-driven programming on X Windows
Event-driven programming on Microsoft Windows
Event-driven programming under Qt
Event-driven programming under MFC
Other event-driven programming models
Limitations of classical event processing models
Reactive programming model
Functional reactive programming
The key interfaces of a reactive program
Pull-versus push-based reactive programming
The IEnumerable/IObservable duality
Converting events to IObservable<T>
The philosophy of our book
Summary
A Tour of Modern C++ and its Key Idioms
The key concerns of the C++ programming language
Zero cost abstraction
Expressivity
Substitutability
Enhancements to C++ for writing better code
Type deduction and inference
Uniform initialization of variables
Variadic templates
Rvalue references 
Move semantics
Smart pointers
Lambda functions
Functors and Lambdas
Composition, currying, and partial function application
Function wrappers
Composing functions together with the pipe operator
Miscellaneous features
Fold expressions
Variant type
Other important topics
Range-based for loops and observables
Summary
Language-Level Concurrency and Parallelism in C++
What is concurrency?
Hello World of concurrency (using std::thread)
Managing threads
Thread launch
Thread join
Passing arguments into a thread
Using Lambdas
Ownership management
Sharing data between threads
Mutexes
Avoiding deadlock
Locking with std::unique_lock
Condition variables
A thread-safe stack data structure
Summary
Asynchronous and Lock-Free Programming in C++
Task-based parallelism in C++
Future and promise
std::packaged_task
std::async
C++ memory model
Memory access and concurrency
The modification contract
Atomic operations and types in C++
Atomic types
std::atomic_flag
std::atomic<bool>
Standard atomic integral types
std::atomic<T*> – pointer arithmetic
std::atomic<> primary class template
Memory ordering
Sequential consistency
Acquire-release ordering
Relaxed ordering
A lock-free data structure  queue
Summary
Introduction to Observables
The GoF Observer pattern
The limitations of the GoF Observer pattern
A holistic look at GoF patterns
The OOP programming model and hierarchies
A Composite/Visitor pattern for expression processing
Flattening the composite for iterative processing
Map and filter operations on the list
Reversing the gaze for Observables!
Summary
Introduction to Event Stream Programming Using C++
What is Stream programming model?
Advantages of the Stream programming model
Applied Stream programming using the Streams library
Lazy evaluation
A simple Stream program
Aggregating values using the Stream paradigm
The STL and the Stream paradigm
A word about the Streams library
Event Stream programming
Advantages of Event Stream programming
The Streamulus library and its programming model
The Streamulus library – a peek into its internals
The Streamulus Library – a look into expression processing
The spreadsheet Library — a change-propagation engine
RaftLib – another Stream-processing library
What do these things have to do with Rx programming?
Summary
Introduction to Data Flow Computation and the RxCpp Library
The data flow computation paradigm
An introduction to the RxCpp library
The RxCpp library and its programming model
A simple Observable/Observer interaction
Filters and transformations with Observables
Streaming values from C++ containers
Creating Observables from scratch
Concatenating Observable Streams
Unsubscribing from Observable Streams
An introduction to marble diagrams for visual representation
RxCpp (Stream) operators
The average operator
The scan operator
Composing operators through the pipe operator
Working with Schedulers
A tale of two operators – flat versus concat map
More operators that are of importance
A peek into the things we haven't covered yet
Summary
RxCpp – the Key Elements
Observables
What's a producer?
Hot versus cold Observables
Hot Observables
Hot Observables and the replay mechanism
Observers and their variants (subscribers)
Subjects
Schedulers
ObserveOn versus SubscribeOn
The RunLoop Scheduler
Operators
Creational operators
Transformation operators
Filtering operators
Combining operators
Error-handling operators
Observable utility operators
Conditional and Boolean operators
Mathematical and aggregate operators
Connectable Observable operators
Summary
Reactive GUI Programming Using Qt/C++
A quick introduction to Qt GUI programming
Qt object model
Signals and slots
Event system
Event handlers
Sending events
Meta-object system
Hello World – Qt program
Qt event model with signals/slots/MOC – an example
Creating a custom widget
Creating the application dialog
Executing the application
Integrating the RxCpp library with the Qt event model
Qt event filter – a reactive approach
Creating the window – setting layouts and alignments
Event type specific observables
An introduction to RxQt
Summary
Design Patterns and Idioms for C++ Rx Programming
The OOP and design patterns movement
Key pattern catalogs
GOF patterns
POSA catalog
The design pattern redux
From design patterns to reactive programming
Flattening the hierarchy to navigate through them
From iterators to observables
The cell pattern
The active object pattern
Resource loan pattern
The event bus pattern
Summary
Reactive Microservices Using C++
The C++ language and web programming
The REST programming model
The C++ REST SDK
HTTP client programming using the C++ REST SDK
HTTP server programming using the C++ REST SDK
Testing the HTTP server using CURL and POSTMAN
The libcurl and the HTTP client programming
Kirk Shoop's CURL Wrapper library
The JSON and HTTP protocols
The C++ REST SDK-based REST server
Invoking REST services using the RxCurl library
A word about the Reactive microservices architecture
Fine-grained services
Polyglot persistence
Independent deployment
Service orchestration and choreography
Reactive web service call
Summary
Advanced Streams and Handling Errors
A short recap of the characteristics of a reactive system
RxCpp error and exception handling operators
Executing an action on an error
Resuming when an error occurs
Retry when an error occurs
Cleanup with the finally() operator
Schedulers and error handling
Event-based Stream handling – some examples
Aggregation based on Stream data
Application event handling example
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
This book will help you learn how to implement the reactive programming paradigm with C++ and build asynchronous and concurrent applications. The book includes real-world problems that you will solve with the reactive programming model. It highlights the way event processing has evolved in the programming world. You will learn about language-level concurrency in C++ and functional reactive programming. Constructs in functional programming and object-oriented programming will enable you to write efficient programs. After this, you will learn about microservices in C++ and create your custom operators for RxCpp.
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.
Chapter 1, Reactive Programming Model – Overview and History, introduces some key data structures of the Rx programming model. It also covers GUI event handling, an overview of reactive programming, and an implementation of GUI versions of different interfaces on top of MFC.
Chapter 2, A Tour of Modern C++ and its Key Idioms, covers C++ features, type inference, variadic templates, rvalue references and move semantics, lambda functions, elementary functional programming, pipeable operators, and implementation of iterators and observers.
Chapter 3, Language-Level Concurrency and Parallelism in C++, discusses the threading library available in the C++ standard. You will learn how to launch and manage a thread, and discuss different aspects of the threading library. This chapter lays a good foundation for concurrency support introduced in Modern C++.
Chapter 4, Asynchronous and Lock-Free Programming in C++, discusses the facilities provided by the standard library for writing task-based parallelism. It also discusses the new multithreading-aware memory model that is available with the Modern C++ language.
Chapter 5, Introduction to Observables, talks about the GoF Observer pattern and explains its shortcomings. You will learn about the GoF Composite/Visitor pattern in the context of modeling an expression tree.
Chapter 6, Introduction to Event Stream Programming Using C++, focuses on the topic of event Stream programming. We will also look at the Streamulus library, which provides a DSEL approach to the manipulation of event Streams, followed by a couple of programs.
Chapter 7, Introduction to Data Flow Computation and the RxCpp Library, starts with a conceptual overview of the data flow computing paradigm and moves quickly to writing some basic RxCpp programs. You will learn about the set of operators supported by the RxCpp library.
Chapter 8, RxCpp – the Key Elements, gives you an understanding of how pieces of the Rx programming model fit together. The chapter starts with Observables and moves on to cover the subscription mechanism and scheduler implementation.
Chapter 9, Reactive GUI Programming Using Qt/C++, deals with the topic of reactive GUI programming using Qt. You will learn about concepts in the Qt framework, such as the Qt object hierarchy, the meta-object system, and signals and slots. Then, you will write an application to handle mouse events and filter them. After this you will also learn advanced topic of how we can create custom reactive operators in RxCpp, should an existing set of operators not suffice for the purpose. This topic also helps you create composite operators by composing the existing operators. This topic is not present in the book, but it is available for download at https://www.packtpub.com/sites/default/files/downloads/Creating_Custom_Operators_in_RxCpp.pdf.
Chapter 10, Design Patterns and Idioms for C++ Rx Programming, delves into the wonderful world of design patterns and idioms. Starting with GOF design patterns, we will move on to reactive programming patterns.
Chapter 11, Reactive Microservices Using C++, covers how the Rx programming model can be used to write reactive microservices using C++. It introduces you to the Microsoft C++ REST SDK and its programming model.
Chapter 12, Advanced Streams and Handling Errors, discusses error handling in RxCpp, along with some of the advanced constructs and operators that handle Streams in the RxCpp library. We will discuss how to continue Streams when an error comes, how to wait for the producer of the Stream to correct the error and continue the sequence, and how to perform common operations that are applicable to both success and error paths.
In order to follow the topics in this book, you need to have a knowledge of C++ programming.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/CPP-Reactive-Programming. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/CPPReactiveProgramming_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The preceding code snippet initializes a structure by the name of WNDCLASS (or WNDCLASSEX for modern systems) with a necessary template for a window."
A block of code is set as follows:
/* close connection to server */XCloseDisplay(display);return 0;}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
/* close connection to server */XCloseDisplay(display);
return 0;
}
Any command-line input or output is written as follows:
$ mkdir css
$ cd css
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "In Windowing parlance, it is called a message loop."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
The X Windows system, Microsoft Windows, and IBM OS/2 Presentation Manager made GUI programming popular on the PC platform. This was a major shift from the character mode user interface and batch process style programming models that existed before them. Responding to events became a major concern for software developers worldwide and platform vendors resorted to the creation of low-level C-based APIs that relied on function pointers and callbacks to enable programmers to handle the events. The programming models were mostly based on the co-operative multithreaded model, and with the advent of better microprocessors, most platforms began to support pre-emptive multithreading. Handling events (and other asynchronous tasks) became more complex and responding to events in the traditional way became less scalable. Even though excellent C++-based GUI toolkits made their appearance, event handling was done mostly using message IDs, function pointer based dispatches, and other low-level techniques. A prominent compiler vendor even tried adding language extensions to the C++ language to enable better Windows programming. Handling events, asynchrony, and associated issues require a fresh look at the problem. Luckily, the Modern C++ standard has support for Functional Programming, language-level concurrency (with a memory model), and better memory management techniques to enable programmers to work with asynchronous data streams (by treating events as streams). This is achieved using a programming model called reactive programming. To put things in perspective, this chapter will outline the following topics:
Event-driven programming model and how it has been implemented in various platforms.
What is reactive programming?
Different models of reactive programming.
Some simple programs to make conceptual understanding better.
The philosophy of our book.
Event-driven programming is a programming model where flow control is determined by events. Examples of events are mouse clicks, key presses, gestures, sensor data, messages from other programs, and so on. An event-driven application has the mechanism to detect events on a near real-time basis, and respond or react to them by invoking the appropriate event handling procedure. Since the bulk of the earlier event processing programs were written using C/C++, they resorted to low-level techniques such as callbacks (using function pointers) to write those event handlers. Later systems such as Visual Basic, Delphi, and other rapid application development tools did add native support for event-driven programming. To make matters more clear, we will take a tour of the event handling mechanism of the various platforms. This will help readers appreciate the issues that reactive programming models are solving (from a GUI programming context).
The Microsoft Foundation class library is still a popular library with which to write Microsoft Windows-based desktop programs. It does have some support for web programming if we mix ActiveX Template Library (ATL) along with it. Being a C++ library, MFC uses a mechanism called Message Mapping to handle events. A sample event handling table given as macros is part of every MFC program:
BEGIN_MESSAGE_MAP(CClockFrame,CFrameWnd) ON_WM_CREATE() ON_WM_PAINT() ON_WM_TIMER()END_MESSAGE_MAP()
The preceding message map will respond to OnCreate, OnPaint, and Ontimer standard Windows API messages. Deep down these message maps are arrays on to which we will use message id as an index for dispatching the events. On closer examination, it is not much different from the standard Windows API messaging model.
Distributed object processing frameworks such as COM+ and CORBA do have their own event processing framework. The COM+ event model is based on the notion of Connection Points (modeled by IConnectionPointContainer/IConnectionPoint interfaces) and CORBA does have its own event service model. The CORBA standard provides both pull-based and push-based event notifications. COM+ and CORBA are beyond the scope of this book and the reader is expected to consult the respective documentation.
The whole purpose of making a tour of the event processing supported by various platforms was to put things into the proper perspective. The event response logic in these platforms is mostly coupled with the platform where the code is written. With the advent of multi-core programming, writing low-level multi-threaded code is difficult and declarative task-based programming models are available with the C++ programming language. But the event sources are mostly outside the C++ standard! The C++ language does not have a standard GUI programming library, an interface standard to access external devices, and so on. What is the way out? Luckily, events and data from external sources can be aggregated into streams (or sequences) and by using functional programming constructs such as Lambda functions can be processed very efficiently. The added bonus is that if we resort to some kind of restrictions regarding the mutability of variables and streams, concurrency, and parallelism are built into the stream processing model.
Simply put, reactive programming is nothing but programming with asynchronous data streams. By applying various operations on stream, we can achieve different computational goals. The primary task in a reactive program is to convert data into streams, regardless of what the source of the data is. While writing modern graphical user interface applications, we process mouse move-and-click events. Currently, most systems get a callback and process these events as and when they happen. Most of the time, the handler does a series of filtering operations before it invokes the action methods associated with the event calls. In this particular context, reactive programming helps us in aggregating the mouse move-and-click events into a collection and sets a filter on them before notifying the handler logic. In this way, the application/handler logic does not get executed unnecessarily.
The stream-processing model is well known, and it is very easy to encode by application developers. Pretty much anything can be converted into a stream. Such candidates include messages, logs, properties, Twitter feeds, blog posts, RSS feeds, and so on. Functional programming techniques are really good at processing streams. A language such as Modern C++, with excellent support for Object/Functional programming, is a natural choice for writing reactive programs. The basic idea behind reactive programming is that there are certain datatypes that represent a value over time. These datatypes (or rather data sequences) are represented as Observable sequences in this programming paradigm. Computations that involve these changing (time-dependent) values will, in turn, themselves have values that change over time, and will need to asynchronously receive notifications (as and when the dependent data changes).
Almost all modern programming languages support functional programming constructs. Functional programming constructs such as Transform, Apply, Filter, Fold, and so on are good for processing streams. Programming asynchronous data streams using functional programming constructs are generally called functional reactive programming (for all practical purposes). The definition given here is an operational one. Consult the work done by Conal Elliott and Paul Hudak as part of the Haskell community to understand the strict definition. Mixing Reactive Programming with FP is gaining traction among developers these days. The Emergence of libraries such as Rx.Net, RxJava, RxJs, and RxCpp and so on is a testimony to this.
Reactive programs can be classified as push-based and pull-based. The pull-based system waits for a demand to push the data streams to the requestor (or subscriber in our case). This is the classic case where the data source is actively polled for more information. This employs the iterator pattern, and IEnumerable <T>/IEnumerator <T> interfaces are specifically designed for such scenarios that are synchronous in nature (the application can block while pulling data). On the other hand, a push-based system aggregates events and pushes through a signal network to achieve the computation. In this case, unlike the pull-based system, data and related updates are handed to the subscriber from the source (Observable sequences in this case). This asynchronous nature is achieved by not blocking the subscriber, but rather making it react to the changes. As you can see, employing this push pattern is more beneficial in rich UI environments where you wouldn't want to block the main UI thread while waiting for some events. This becomes ideal, thus making reactive programs responsive.