fork download
  1. //SRThreadPool.h
  2.  
  3. #pragma once
  4.  
  5. #include "SRTask.h"
  6.  
  7. #include <boost/thread.hpp>
  8. #include <deque>
  9.  
  10. class ThreadPool;
  11.  
  12. class ThreadFunc
  13. {
  14. public:
  15. ThreadFunc(ThreadPool& pool): threadpool(pool) {}
  16.  
  17. void operator()();
  18.  
  19. private:
  20. ThreadFunc();
  21. ThreadPool& threadpool;
  22. };
  23.  
  24. class ThreadPool
  25. {
  26. friend class ThreadFunc;
  27. public:
  28. ThreadPool(size_t nbOfThreads);
  29.  
  30. void SubmitTask(SRTask& task);
  31.  
  32. private:
  33. ThreadPool();
  34.  
  35. bool stop;
  36. size_t numThreads;
  37.  
  38. boost::mutex queueMutex;
  39. std::deque<SRTask> taskQueue;
  40. std::vector<boost::thread> threads;
  41. };
  42.  
  43. // SRThreadPool.cpp
  44. #include "Precompiled.h"
  45. #include "SRThreadPool.h"
  46.  
  47. void ThreadFunc::operator()()
  48. {
  49. while(true)
  50. {
  51. if(threadpool.stop)
  52. break;
  53.  
  54. // Might want to use boost::optional here
  55. threadpool.queueMutex.lock();
  56. if(threadpool.taskQueue.size() > 0)
  57. {
  58. SRTask t = threadpool.taskQueue.front();
  59. threadpool.taskQueue.pop_front();
  60. threadpool.queueMutex.unlock();
  61.  
  62. t();
  63. }
  64. else
  65. {
  66. threadpool.queueMutex.unlock();
  67. }
  68. }
  69. }
  70.  
  71. ThreadPool::ThreadPool(size_t nbOfThreads): numThreads(nbOfThreads), stop(false), threads(0)
  72. {
  73. for(size_t i=0; i<numThreads; i++)
  74. {
  75. threads.emplace_back(boost::thread(ThreadFunc(*this)));
  76. }
  77. }
  78.  
  79. void ThreadPool::SubmitTask(SRTask& task)
  80. {
  81. queueMutex.lock();
  82. taskQueue.push_back(task);
  83. queueMutex.unlock();
  84. }
  85.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty