June 2018
Intermediate to advanced
348 pages
8h 45m
English
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 ...