azurenote

google c++ tutorial chapter2 ex1, multithreaded

Oct 29th, 2013
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <cstdint>
  2. #include <chrono>
  3. #include <iostream>
  4. #include <atomic>
  5. #include <thread>
  6. #include <vector>
  7.  
  8. using namespace std;
  9. using namespace std::chrono;
  10. typedef duration<float> fsec;
  11.  
  12. auto started = steady_clock::now();
  13. atomic<int> counter = 0;
  14.  
  15. inline int GetNumber()
  16. {
  17.     return ++counter;
  18. }
  19.  
  20. inline int64_t SigmaN(int64_t n) // to avoid overflow
  21. {
  22.     return n * (n + 1) >> 1;
  23. }
  24.  
  25. int SerialN(int n)
  26. {
  27.     for (int i = 0; i < n ; ++i)
  28.     {
  29.         if (SigmaN(i) == n)
  30.             return i;
  31.     }
  32.  
  33.     return 0;
  34. }
  35.  
  36. int IsPerfectSquare(int n)
  37. {
  38.     if (n < 0)
  39.         return 0;
  40.  
  41.     int root = (int)(sqrt(n));
  42.  
  43.     return n == root * root ?
  44.                     root : 0;
  45. }
  46.  
  47. void Work()
  48. {
  49.     while (true)
  50.     {
  51.         int number = GetNumber();
  52.  
  53.         if (0 > number)
  54.             break; // until overflow
  55.  
  56.         int root = IsPerfectSquare(number);
  57.  
  58.         if (0 < root)
  59.         {
  60.             auto last_of_serial = SerialN(number);
  61.  
  62.             if (0 < last_of_serial)
  63.             {
  64.                 //print elapsed time
  65.                 printf("%d = %d^2 = sum(1..%d)\n %0.2f sec\n",
  66.                     number, root, last_of_serial,
  67.                     duration_cast<fsec>(steady_clock::now() - started).count()
  68.                     );
  69.             }
  70.         }
  71.     }//while
  72. }
  73.  
  74.  
  75.  
  76. int main (void)
  77. {
  78.     const size_t sizeofThread = 9;
  79.  
  80.     vector<thread> workers;
  81.  
  82.     for (int i = 0; i < sizeofThread; ++i)
  83.     {
  84.         workers.push_back(thread(Work));
  85.     }
  86.  
  87.     for (auto& t : workers)
  88.         t.join();
  89. }
Add Comment
Please, Sign In to add comment