Guest User

Untitled

a guest
May 15th, 2014
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1.  
  2. #include <thread>
  3. #include <atomic>
  4.  
  5. #define THREADPOOL_THREADMAX (16)
  6.  
  7. class ThreadPool
  8. {
  9. public:
  10.     typedef uint64_t Progress;
  11.  
  12.     template<typename T>
  13.     void Start(T Function, const size_t NewThreadNum)
  14.     {
  15.         if (ThreadNum > 0) return;//läuft schon
  16.         ThreadNum = NewThreadNum;
  17.  
  18.         for (int i = 0; i < ThreadNum; ++i)
  19.             Thread[i] = std::thread(Function);
  20.     }
  21.     void Join()
  22.     {
  23.         for (int i = 0; i < ThreadNum; ++i)
  24.             Thread[i].join();
  25.         ThreadNum = 0;
  26.     }
  27.  
  28.     void Sync(Progress& LocalProgress)
  29.     {
  30.         ++LocalProgress;
  31.         if ((FinishCounter.fetch_add(1) + 1) == ThreadNum)
  32.         {
  33.             FinishCounter = 0;
  34.             ++GlobalProgress;
  35.         }
  36.  
  37.         while (LocalProgress > GlobalProgress)
  38.             std::this_thread::sleep_for(std::chrono::milliseconds(0));
  39.     }
  40.  
  41. private:
  42.     size_t ThreadNum = 0;
  43.  
  44.     std::thread Thread[THREADPOOL_THREADMAX];
  45.     std::atomic<size_t> FinishCounter = 0;
  46.     Progress GlobalProgress = 0;
  47. };
Advertisement
Add Comment
Please, Sign In to add comment