Advertisement
P22DX

async.cpp

Jun 11th, 2020
1,129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. /**
  2.  * async multi threading with c++
  3.  * flag : -pthread -std=c++0x
  4.  */
  5.  
  6. #include <iostream> // std::cout
  7. #include <unistd.h> // sleep();
  8. #include <future> // std::async
  9.  
  10. class MyClass {
  11.     public:
  12.         auto doStuffSoLong()->int
  13.         {
  14.             sleep(7);
  15.             std::cout << "1" << std::endl << std::flush; //dont buffer
  16.             return 0;
  17.         }
  18.         auto doAnotherStuff()->int
  19.         {
  20.             std::cout << "2" << std::endl << std::flush; //dont buffer
  21.             return 0;
  22.         }
  23.         auto doAnotherLongStuff(const std::string &param)->int
  24.         {
  25.             sleep(3);
  26.             std::cout << "3" << std::endl << std::flush; //dont buffer
  27.             return 0;
  28.         }
  29. };
  30.  
  31. int main()
  32. {
  33.     sleep(3); // give a time to open task manager
  34.     MyClass app;
  35.  
  36.     auto thread1 = std::async(std::launch::async, &MyClass::doStuffSoLong, &app);
  37.     auto thread2 = std::async(std::launch::async, &MyClass::doAnotherStuff, &app);
  38.     auto thread3 = std::async(std::launch::async, &MyClass::doAnotherLongStuff, &app, "hello world");
  39.     if(thread1.get() == 0) std::cout << "thread 1 succes" << std::endl;
  40.     if(thread2.get() == 0) std::cout << "thread 2 succes" << std::endl;
  41.     if(thread3.get() == 0) std::cout << "thread 3 succes" << std::endl;
  42.  
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement