ThisIsAreku

C++ 11 Threading test

May 15th, 2014
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include <thread>
  2. #include <iostream>
  3.  
  4.  
  5. using namespace std;
  6.  
  7. void test_thread(int id)
  8. {
  9.     int wait = 5 -id;
  10.     std::cout << "echo from thread " << id << " with " << wait << " delay" << std::endl;
  11.     std::this_thread::sleep_for (std::chrono::seconds(wait));
  12.     std::cout << "end from thread " << id << " with " << wait << " delay" << std::endl;
  13. }
  14. void start_thread(int concurentThreadsSupported)
  15. {
  16.     std::cout << "Using " << concurentThreadsSupported << " concurrent threads" << std::endl;
  17.     std::thread * threads = new std::thread[concurentThreadsSupported];
  18.     for (int i = 0; i < concurentThreadsSupported; ++i)
  19.     {
  20.         std::cout << "CREATE " << i << std::endl;
  21.         threads[i] = std::thread(test_thread, i);
  22.         std::cout << "CREATED " << i << std::endl;
  23.         std::this_thread::sleep_for (std::chrono::seconds(1));
  24.     }
  25.     std::this_thread::sleep_for (std::chrono::seconds(concurentThreadsSupported+2));
  26.     std::cout << "echo from thread BASE" << std::endl;
  27.     for (int i = 0; i < concurentThreadsSupported; ++i)
  28.     {
  29.         std::cout << "START " << i << std::endl;
  30.         threads[i].join();
  31.         std::cout << "OK " << i << std::endl;
  32.     }
  33.     std::cout << "end from thread BASE" << std::endl;
  34.     delete [] threads;
  35. }
  36.  
  37. int main()
  38. {
  39.     unsigned concurentThreadsSupported = std::thread::hardware_concurrency();
  40.     if(concurentThreadsSupported == 0){
  41.         std::cout << "Can't get number of hardware threads" << std::endl;
  42.         concurentThreadsSupported = 1;
  43.     }
  44.     std::cout << "echo from MAIN" << std::endl;
  45.     start_thread(concurentThreadsSupported);
  46.     std::cout << "end from MAIN" << std::endl;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment