CThreadHelper.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. std::mutex rtinm;
  22. int currentTask;
  23. int amount;
  24. int threads;
  25. std::vector<Task> *tasks;
  26. void processTasks();
  27. };
  28. template<typename Payload>
  29. class ThreadPool
  30. {
  31. public:
  32. using Task = std::function<void(std::shared_ptr<Payload>)>;
  33. using Tasks = std::vector<Task>;
  34. ThreadPool(Tasks * tasks_, std::vector<std::shared_ptr<Payload>> context_)
  35. : currentTask(0),
  36. amount(tasks_->size()),
  37. threads(context_.size()),
  38. tasks(tasks_),
  39. context(context_)
  40. {}
  41. void run()
  42. {
  43. std::vector<boost::thread> group;
  44. for(size_t i=0; i<threads; i++)
  45. {
  46. std::shared_ptr<Payload> payload = context.at(i);
  47. group.emplace_back(std::bind(&ThreadPool::processTasks, this, payload));
  48. }
  49. for (auto & thread : group)
  50. thread.join();
  51. //thread group deletes threads, do not free manually
  52. }
  53. private:
  54. std::mutex rtinm;
  55. size_t currentTask;
  56. size_t amount;
  57. size_t threads;
  58. Tasks * tasks;
  59. std::vector<std::shared_ptr<Payload>> context;
  60. void processTasks(std::shared_ptr<Payload> payload)
  61. {
  62. while(true)
  63. {
  64. size_t pom;
  65. {
  66. std::unique_lock<std::mutex> lock(rtinm);
  67. if((pom = currentTask) >= amount)
  68. break;
  69. else
  70. ++currentTask;
  71. }
  72. (*tasks)[pom](payload);
  73. }
  74. }
  75. };
  76. /// Sets thread name that will be used for both logs and debugger (if supported)
  77. /// WARNING: on Unix-like systems this method should not be used for main thread since it will also change name of the process
  78. void DLL_LINKAGE setThreadName(const std::string &name);
  79. /// Sets thread name for use in logging only
  80. void DLL_LINKAGE setThreadNameLoggingOnly(const std::string &name);
  81. /// Returns human-readable thread name that was set before, or string form of system-provided thread ID if no human-readable name was set
  82. std::string DLL_LINKAGE getThreadName();
  83. VCMI_LIB_NAMESPACE_END