Wednesday, 24 June 2020

Multithreading :1.Create thread

We will be using std::thread class to create threads.
std:thread is introduced in C++11.
We can start creating threads by including the thread header file. To create a thread, we need to pass the code that needs to be executed in the constructor of the thread.
As soon as the thread object is created, a new thread is launched, which will execute the code passed to the constructor.


The constructor takes

  • a function object
  • a function pointer
  • a  lambda expression

#include<thread>
#include<iostream>
using namespace std;
class print_obj {
public:
void operator()(int max)
{
cout << "Thread with function object" << endl;;
for (int i = 0; i < max; i++)
{
cout << i << endl;
}
}
};
void main()
{
//creating a thread with a function pointer
thread t1(print, 50);
//creating a thread with a function object
thread t2(print_obj(), 100);
//below is a lambda expression
auto printlambda = [](int max) {
cout << "thread with lambda function" << endl;
for (int i = 0; i < max; i++)
cout << i << endl;
};
//creating a thread with a lambda
thread t3(printlambda, 150);
}


No comments:

Post a Comment