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

Passing arguments into a thread

So, we have figured out how to launch and wait over a thread. Now, let's see how to pass arguments into a thread initialization function. Let's look at an example to find the factorial of a number:

class Factorial 
{ 
private: 
    long long myFact; 
     
public: 
    Factorial() : myFact(1) 
    { 
    } 
     
    void operator() (int number) 
    { 
        myFact = 1; 
        for (int i = 1; i <= number; ++i) 
        { 
            myFact *= i; 
        } 
        std::cout << "Factorial of " << number << " is " << myFact; 
    } 
}; 
 
int main() 
{ 
    Factorial fact; 
     
    std::thread t1(fact, 10); 
     
    t1.join(); 
} 
 

From this example, it is clear that passing arguments into a thread function or a thread callable object can be achieved by passing additional arguments into an std::thread() declaration. One thing we must keep ...

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