CThreadHelper.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "StdInc.h"
  2. #include "CThreadHelper.h"
  3. #ifdef _WIN32
  4. #include <windows.h>
  5. #else
  6. #include <sys/prctl.h>
  7. #endif
  8. /*
  9. * CThreadHelper.cpp, part of VCMI engine
  10. *
  11. * Authors: listed in file AUTHORS in main folder
  12. *
  13. * License: GNU General Public License v2.0 or later
  14. * Full text of license available in license.txt file, in main folder
  15. *
  16. */
  17. CThreadHelper::CThreadHelper(std::vector<boost::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. for(int i=0;i<threads;i++)
  27. grupa.create_thread(boost::bind(&CThreadHelper::processTasks,this));
  28. grupa.join_all();
  29. }
  30. void CThreadHelper::processTasks()
  31. {
  32. int pom;
  33. while(true)
  34. {
  35. {
  36. boost::unique_lock<boost::mutex> lock(rtinm);
  37. if((pom = currentTask) >= amount)
  38. break;
  39. else
  40. ++currentTask;
  41. }
  42. (*tasks)[pom]();
  43. }
  44. }
  45. void setThreadName(long threadID, const std::string &name)
  46. {
  47. #ifdef _WIN32
  48. //follows http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  49. const DWORD MS_VC_EXCEPTION=0x406D1388;
  50. #pragma pack(push,8)
  51. typedef struct tagTHREADNAME_INFO
  52. {
  53. DWORD dwType; // Must be 0x1000.
  54. LPCSTR szName; // Pointer to name (in user addr space).
  55. DWORD dwThreadID; // Thread ID (-1=caller thread).
  56. DWORD dwFlags; // Reserved for future use, must be zero.
  57. } THREADNAME_INFO;
  58. #pragma pack(pop)
  59. THREADNAME_INFO info;
  60. info.dwType = 0x1000;
  61. info.szName = name.c_str();
  62. info.dwThreadID = threadID;
  63. info.dwFlags = 0;
  64. __try
  65. {
  66. RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
  67. }
  68. __except(EXCEPTION_EXECUTE_HANDLER)
  69. {
  70. }
  71. #else
  72. prctl(PR_SET_NAME, name.c_str(), 0, 0, 0);
  73. #endif
  74. }