CThreadHelper.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * CThreadHelper.cpp, 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. #include "StdInc.h"
  11. #include "CThreadHelper.h"
  12. #ifdef VCMI_WINDOWS
  13. #include <windows.h>
  14. #elif !defined(VCMI_APPLE) && !defined(VCMI_FREEBSD) && !defined(VCMI_HURD)
  15. #include <sys/prctl.h>
  16. #endif
  17. CThreadHelper::CThreadHelper(std::vector<std::function<void()> > *Tasks, int Threads)
  18. {
  19. currentTask = 0; amount = Tasks->size();
  20. tasks = Tasks;
  21. threads = Threads;
  22. }
  23. void CThreadHelper::run()
  24. {
  25. boost::thread_group grupa;
  26. std::vector<boost::thread *> thr;
  27. for(int i=0;i<threads;i++)
  28. thr.push_back(grupa.create_thread(std::bind(&CThreadHelper::processTasks,this)));
  29. grupa.join_all();
  30. for(auto thread : thr)
  31. delete thread;
  32. }
  33. void CThreadHelper::processTasks()
  34. {
  35. while(true)
  36. {
  37. int pom;
  38. {
  39. boost::unique_lock<boost::mutex> lock(rtinm);
  40. if((pom = currentTask) >= amount)
  41. break;
  42. else
  43. ++currentTask;
  44. }
  45. (*tasks)[pom]();
  46. }
  47. }
  48. // set name for this thread.
  49. // NOTE: on *nix string will be trimmed to 16 symbols
  50. void setThreadName(const std::string &name)
  51. {
  52. #ifdef VCMI_WINDOWS
  53. #ifndef __GNUC__
  54. //follows http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  55. const DWORD MS_VC_EXCEPTION=0x406D1388;
  56. #pragma pack(push,8)
  57. typedef struct tagTHREADNAME_INFO
  58. {
  59. DWORD dwType; // Must be 0x1000.
  60. LPCSTR szName; // Pointer to name (in user addr space).
  61. DWORD dwThreadID; // Thread ID (-1=caller thread).
  62. DWORD dwFlags; // Reserved for future use, must be zero.
  63. } THREADNAME_INFO;
  64. #pragma pack(pop)
  65. THREADNAME_INFO info;
  66. info.dwType = 0x1000;
  67. info.szName = name.c_str();
  68. info.dwThreadID = -1;
  69. info.dwFlags = 0;
  70. __try
  71. {
  72. RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
  73. }
  74. __except(EXCEPTION_EXECUTE_HANDLER)
  75. {
  76. }
  77. #else
  78. //not supported
  79. #endif
  80. #elif defined(__linux__)
  81. prctl(PR_SET_NAME, name.c_str(), 0, 0, 0);
  82. #endif
  83. }