Book Image

C++ Reactive Programming

By : Praseed Pai, Peter Abraham
Book Image

C++ Reactive Programming

By: Praseed Pai, Peter Abraham

Overview of this book

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).
Table of Contents (20 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Using Lambdas


Now, let's see the usefulness of Lambda expressions for multithreading. In the following code, we are going to create five threads and put those into a vector container. Each thread will be using a Lambda function as the initialization function. The threads initialized in the following code are capturing the loop index by value:

int main() 
{ 
    std::vector<std::thread> threads; 
 
    for (int i = 0; i < 5; ++i) 
    { 
        threads.push_back(std::thread( [i]() { 
            std::cout << "Thread #" << i << std::endl; 
        })); 
    } 
 
    std::cout << "nMain function"; 
 
    std::for_each(threads.begin(), threads.end(), [](std::thread &t) { 
        t.join(); 
    }); 
} 

The vector container threads store five threads that have been created inside the loop. They are joined at the end of the main() function once the execution is over. The output for the preceding code may look as follows:

Thread # Thread # Thread # Thread # Thread...