You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

threadpool.cpp 992B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "threadpool.h"
  2. namespace vtk {
  3. ThreadPool::ThreadPool() {
  4. }
  5. ThreadPool::ThreadPool(ThreadPool const& copy) {
  6. }
  7. ThreadPool& ThreadPool::operator=(ThreadPool const& copy) {
  8. return *this;
  9. }
  10. ThreadPool& ThreadPool::getInstance() {
  11. static ThreadPool instance;
  12. return instance;
  13. }
  14. void ThreadPool::addThreads(const int &count) {
  15. for (int i = 0; i < count; ++i) {
  16. mThreads.push_back(std::thread(&ThreadPool::threadIdle, this));
  17. }
  18. }
  19. void ThreadPool::threadIdle() {
  20. // Idle until something appears in the job queue, then run it
  21. std::function<void()> job;
  22. while(true) {
  23. {
  24. std::unique_lock<std::mutex> lock(mQueueMutex);
  25. mCondition.wait(lock, [&]{return !mQueue.empty();});
  26. job = mQueue.front();
  27. mQueue.pop();
  28. }
  29. job();
  30. }
  31. }
  32. void ThreadPool::addJob(std::function<void ()> newJob) {
  33. {
  34. std::unique_lock<std::mutex> lock(mQueueMutex);
  35. mQueue.push(newJob);
  36. }
  37. mCondition.notify_one();
  38. }
  39. int ThreadPool::threadCount() {
  40. return mThreads.size();
  41. }
  42. }