SilverTES

Multithreading Standard <thread> : C++

Jan 6th, 2017
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3.  
  4. template <class M = std::string, class E = int>
  5. E log(M msg, E error = 0)
  6. {
  7.     std::cout << msg;
  8.     return error;
  9. }
  10.  
  11. class DisplayThread
  12. {
  13.     public:
  14.  
  15.         void operator()()
  16.         {
  17.             //std::cout << "Current thread  ID = " << std::this_thread::get_id() << "\n";
  18.             for (int i = 0; i < 10; i++)
  19.                 log("<OBJECTS>\n");
  20.         }
  21. };
  22.  
  23. void thread_func()
  24. {
  25.     //std::cout << "Current thread  ID = " << std::this_thread::get_id() << "\n";
  26.     for (int i = 0; i < 10; i++)
  27.         log("<POINTER>\n");
  28. }
  29.  
  30. int main()
  31. {
  32.     // use Function Pointer !
  33.     std::thread threadFuncPointer(thread_func);
  34.  
  35.     // use Function Objects !
  36.     std::thread threadFuncObjects((DisplayThread()));
  37.  
  38.     // use Lambda functions !
  39.     std::thread threadFuncLambda([]()
  40.     {
  41.         //std::cout << "Current thread  ID = " << std::this_thread::get_id() << "\n";
  42.         for (int i = 0; i < 10; i++)
  43.             log("<LAMBDA>\n");
  44.     });
  45.  
  46.     for (int i = 0; i < 100; i++)
  47.         log("<MAIN>\n");
  48.  
  49.     std::cout << "Pointer ID = " << threadFuncPointer.get_id() << "\n";
  50.     std::cout << "Objects ID = " << threadFuncObjects.get_id() << "\n";
  51.     std::cout << "Lambda  ID = " << threadFuncLambda.get_id() << "\n";
  52.  
  53.     threadFuncPointer.join();
  54.     threadFuncObjects.join();
  55.     threadFuncLambda.join();
  56.  
  57.     std::cout << "Current thread  ID = " << std::this_thread::get_id() << "\n";
  58.  
  59.     return log("- End of main()\n");
  60. }
Advertisement
Add Comment
Please, Sign In to add comment