CThreadHelper.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * CThreadHelper.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. ///DEPRECATED
  12. /// Can assign CPU work to other threads/cores
  13. class DLL_LINKAGE CThreadHelper
  14. {
  15. public:
  16. typedef std::function<void()> Task;
  17. CThreadHelper(std::vector<std::function<void()> > *Tasks, int Threads);
  18. void run();
  19. private:
  20. boost::mutex rtinm;
  21. int currentTask, amount, threads;
  22. std::vector<Task> *tasks;
  23. void processTasks();
  24. };
  25. template<typename Payload>
  26. class ThreadPool
  27. {
  28. public:
  29. using Task = std::function<void(std::shared_ptr<Payload>)>;
  30. using Tasks = std::vector<Task>;
  31. ThreadPool(Tasks * tasks_, std::vector<std::shared_ptr<Payload>> context_)
  32. : currentTask(0),
  33. amount(tasks_->size()),
  34. threads(context_.size()),
  35. tasks(tasks_),
  36. context(context_)
  37. {}
  38. void run()
  39. {
  40. boost::thread_group grupa;
  41. for(size_t i=0; i<threads; i++)
  42. {
  43. std::shared_ptr<Payload> payload = context.at(i);
  44. grupa.create_thread(std::bind(&ThreadPool::processTasks, this, payload));
  45. }
  46. grupa.join_all();
  47. //thread group deletes threads, do not free manually
  48. }
  49. private:
  50. boost::mutex rtinm;
  51. size_t currentTask, amount, threads;
  52. Tasks * tasks;
  53. std::vector<std::shared_ptr<Payload>> context;
  54. void processTasks(std::shared_ptr<Payload> payload)
  55. {
  56. while(true)
  57. {
  58. size_t pom;
  59. {
  60. boost::unique_lock<boost::mutex> lock(rtinm);
  61. if((pom = currentTask) >= amount)
  62. break;
  63. else
  64. ++currentTask;
  65. }
  66. (*tasks)[pom](payload);
  67. }
  68. }
  69. };
  70. void DLL_LINKAGE setThreadName(const std::string &name);