Multithreading in C++

Multithreading support was introduced in C+11. Prior to C++11, we had to use POSIX threads or p threads library in C. While this library did the job the lack of any standard language provided feature-set caused serious portability issues. C++ 11 did away with all that and gave us std::thread. The thread classes and related functions are defined in the thread header file.

std::thread is the thread class that represents a single thread in C++. To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object. Once the object is created a new thread is launched which will execute the code specified in callable.

A callable can be either of the three

  • A function pointer
  • A function object
  • A lambda expression
    • After defining callable, pass it to the constructor.

      import<thread>
      std::thread thread_object(callable)

      Launching thread using function pointer
      The following code snippet demonstrates how this is done



      void foo(param)
      {
          // Do something
      }
        
      // The parameters to the function are put after the comma
      std::thread thread_obj(foo, params);

      Launching thread using lambda expression

      The following code snippet demonstrates how this is done

      // Define a lamda expression
      auto f = [](params) {
          // Do Something
      };
        
      // Pass f and its parameters to thread 
      // object constructor as
      std::thread thread_object(f, params);

      We can also pass lambda functions directly to the constructor.

      std::thread thread_object([](params) {
          // Do Something
      };, params);

      Launching threads using function objects

      The following code snippet demonstrates how this is done

      // Define the class of function object
      class fn_object_class {
          // Overload () operator
          void operator()(params)
          {
              // Do Something
          }
      }
        
      // Create thread object
      std::thread thread_object(fn_class_object(), params)

      Waiting for threads to finish

      Once a thread has started we may need to wait for the thread to finish before we can take some action. For instance, if we allocate the task of initializing the GUI of an application to a thread, we need to wait for the thread to finish to ensure that the GUI has loaded properly.

      To wait for a thread use the std::thread::join() function. This function makes the current thread wait until the thread identified by *this has finished executing.
      For instance, to block the main thread until thread t1 has finished we would do

      int main()
      {
          // Start thread t1
          std::thread t1(callable);
        
          // Wait for t1 to finish
          t1.join();
        
          // t1 has finished do other stuff
        
          ...
      }

      A Complete C++ Program

      A C++ program is given below. It launches three thread from the main function. Each thread is called using one of the callable objects specified above.

      // CPP program to demonstrate multithreading
      // using three different callables.
      #include <iostream>
      #include <thread>
      using namespace std;
        
      // A dummy function
      void foo(int Z)
      {
          for (int i = 0; i < Z; i++) {
              cout << "Thread using function"
                     " pointer as callable\n";
          }
      }
        
      // A callable object
      class thread_obj {
      public:
          void operator()(int x)
          {
              for (int i = 0; i < x; i++)
                  cout << "Thread using function"
                        " object as  callable\n";
          }
      };
        
      int main()
      {
          cout << "Threads 1 and 2 and 3 "
               "operating independently" << endl;
        
          // This thread is launched by using 
          // function pointer as callable
          thread th1(foo, 3);
        
          // This thread is launched by using
          // function object as callable
          thread th2(thread_obj(), 3);
        
          // Define a Lambda Expression
          auto f = [](int x) {
              for (int i = 0; i < x; i++)
                  cout << "Thread using lambda"
                   " expression as callable\n";
          };
        
          // This thread is launched by using 
          // lamda expression as callable
          thread th3(f, 3);
        
          // Wait for the threads to finish
          // 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 (Machine Dependent)

      Threads 1 and 2 and 3 operating independently                                                       
      Thread using function pointer as callable                                                           
      Thread using lambda expression as callable                                                          
      Thread using function pointer as callable                                                           
      Thread using lambda expression as callable                                                          
      Thread using function object as  callable                                                          
      Thread using lambda expression as callable                                                          
      Thread using function pointer as callable                                                          
      Thread using function object as  callable                                                           
      Thread using function object as  callable
      

      Note:
      To compile programs with std::thread support use

      g++ -std=c++11 -pthread
      

      References
      cppreference – thread



      My Personal Notes arrow_drop_up

      Intern at GeeksForGeeks

      If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

      Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.





      Practice Tags :
      Article Tags :

      Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2.5 Average Difficulty : 2.5/5.0
Based on 4 vote(s)






User Actions