Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2017
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. #include <chrono>
  2. #include <thread>
  3. #include <iostream>
  4. #include <vector>
  5.  
  6. using namespace std;
  7.  
  8. bool timeout = false;
  9.  
  10. int main (int argc, char* argv[])
  11. {
  12. int delay = 0;
  13. if (argc == 2)
  14. {
  15. delay = atoi (argv[1]);
  16. }
  17.  
  18. if (delay > 0)
  19. {
  20. cout << "Will run for: " << delay << " milliseconds." << endl;
  21.  
  22. thread t ([&] () {
  23. this_thread::sleep_for (chrono::milliseconds (delay));
  24. timeout = true;
  25. });
  26. t.detach ();
  27. }
  28. else
  29. {
  30. cout << "Will run forever." << endl;
  31. }
  32.  
  33. const int n = thread::hardware_concurrency ();
  34. cout << "Using " << n << " thread(s)." << endl;
  35.  
  36. // using vector as MSVC doesn't support variable length array
  37. vector <thread> workers;
  38. workers.reserve (n);
  39. for (int i = 0; i < n; ++i)
  40. {
  41. workers.push_back (thread ([] () {
  42.  
  43. // volatile is mandatory for GCC release build
  44. volatile int count = 0;
  45. while (!timeout)
  46. {
  47. count ++;
  48. }
  49. }));
  50. }
  51.  
  52. for (auto &worker : workers)
  53. {
  54. worker.join ();
  55. }
  56.  
  57. return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement