CThreadHelper.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. VCMI_LIB_NAMESPACE_BEGIN
  12. ///DEPRECATED
  13. /// Can assign CPU work to other threads/cores
  14. class DLL_LINKAGE CThreadHelper
  15. {
  16. public:
  17. using Task = std::function<void()>;
  18. CThreadHelper(std::vector<std::function<void()> > *Tasks, int Threads);
  19. void run();
  20. private:
  21. boost::mutex rtinm;
  22. int currentTask, amount, threads;
  23. std::vector<Task> *tasks;
  24. void processTasks();
  25. };
  26. template<typename Payload>
  27. class ThreadPool
  28. {
  29. public:
  30. using Task = std::function<void(std::shared_ptr<Payload>)>;
  31. using Tasks = std::vector<Task>;
  32. ThreadPool(Tasks * tasks_, std::vector<std::shared_ptr<Payload>> context_)
  33. : currentTask(0),
  34. amount(tasks_->size()),
  35. threads(context_.size()),
  36. tasks(tasks_),
  37. context(context_)
  38. {}
  39. void run()
  40. {
  41. std::vector<boost::thread> group;
  42. for(size_t i=0; i<threads; i++)
  43. {
  44. std::shared_ptr<Payload> payload = context.at(i);
  45. group.emplace_back(std::bind(&ThreadPool::processTasks, this, payload));
  46. }
  47. for (auto & thread : group)
  48. thread.join();
  49. //thread group deletes threads, do not free manually
  50. }
  51. private:
  52. boost::mutex rtinm;
  53. size_t currentTask, amount, threads;
  54. Tasks * tasks;
  55. std::vector<std::shared_ptr<Payload>> context;
  56. void processTasks(std::shared_ptr<Payload> payload)
  57. {
  58. while(true)
  59. {
  60. size_t pom;
  61. {
  62. boost::unique_lock<boost::mutex> lock(rtinm);
  63. if((pom = currentTask) >= amount)
  64. break;
  65. else
  66. ++currentTask;
  67. }
  68. (*tasks)[pom](payload);
  69. }
  70. }
  71. };
  72. void DLL_LINKAGE setThreadName(const std::string &name);
  73. VCMI_LIB_NAMESPACE_END