Skip to Content
C++ Reactive Programming
book

C++ Reactive Programming

by Praseed Pai, Peter Abraham
June 2018
Intermediate to advanced
348 pages
8h 45m
English
Packt Publishing
Content preview from C++ Reactive Programming

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Functional Programming in C++

Functional Programming in C++

Ivan Cukic

Publisher Resources

ISBN: 9781788629775Supplemental Content