Book Image

Learning C++ Functional Programming

By : Wisnu Anggoro
5 (1)
Book Image

Learning C++ Functional Programming

5 (1)
By: Wisnu Anggoro

Overview of this book

Functional programming allows developers to divide programs into smaller, reusable components that ease the creation, testing, and maintenance of software as a whole. Combined with the power of C++, you can develop robust and scalable applications that fulfill modern day software requirements. This book will help you discover all the C++ 17 features that can be applied to build software in a functional way. The book is divided into three modules—the first introduces the fundamentals of functional programming and how it is supported by modern C++. The second module explains how to efficiently implement C++ features such as pure functions and immutable states to build robust applications. The last module describes how to achieve concurrency and apply design patterns to enhance your application’s performance. Here, you will also learn to optimize code using metaprogramming in a functional way. By the end of the book, you will be familiar with the functional approach of programming and will be able to use these techniques on a daily basis.
Table of Contents (15 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Synchronizing the threads using mutex


As of now, we have successfully executed a multithreading code. However, a problem will occur if we consume a shared object and manipulate it inside the thread. It is called synchronization. In this section, we will try to avoid this problem by applying a mutex technique.

Avoiding synchronization issues

As we discussed earlier, in this section, we have to ensure that the shared object we run in the thread gives the correct value when it is executing. Let's suppose we have a global variable named counter and we plan to increase its value in all the five threads we have. Each thread will execute 10000 times increment iteration, so we expect to get 50000 as a result for all five threads. The code is as follows:

    /* notsync.cpp */
    #include <thread>
    #include <iostream>

    using namespace std;

    auto main() -> int
    {
      cout << "[notsync.cpp]" << endl;

      int counter = 0;

      thread threads[5];

      for...