google.com, pub-4617457846989927, DIRECT, f08c47fec0942fa0 Learn to enjoy every minute of your life.Only I can change my life.: The multi threading concept in C++ with an example

Tuesday, December 17, 2019

The multi threading concept in C++ with an example

The multi threading concept in C++ with an example:

#include
#include
using namespace std;
// function to be used in callable
void func_dummy(int N)
 {

  for (int i = 0; i < N; i++) {
  cout << "Thread 1 :: callable => function pointer\n";
   }

 }
 
// A callable object

class thread_obj {

 public:

   void operator()(int n) {

       for (int i = 0; i < n; i++)

           cout << "Thread 2 :: callable => function object\n";

   }

};

int main()
{
// Define a Lambda Expression
auto f = [](int n) {
   for (int i = 0; i < n; i++)
   cout << "Thread 3 :: callable => lambda expression\n";
   };
//launch thread using function pointer as callable
thread th1(func_dummy, 2);
// launch thread using function object as callable
thread th2(thread_obj(), 2);
//launch thread using lambda expression as callable
thread th3(f, 2);
// Wait for thread t1 to finish
 th1.join();
// Wait for thread t2 to finish
th2.join();
// Wait for thread t3 to finish
th3.join();
return 0;
}

Output:

Thread 1 :: callable => function pointer
Thread 1 :: callable => function pointer
Thread 3 :: callable => lambda expression
Thread 3 :: callable => lambda expression
Thread 2 :: callable => function object
Thread 2 :: callable => function object

No comments:

Post a Comment

हिम्मत

 अंधेरे में एक करोड का हीरा गिर गया था, उसे ढूंढने के लिए पाँच रूपएं की मोमबत्ती ने सहयोग किया। अभी बताओ वह पाँच रूपएं की एक छोटी सी मोमबत्त...