CThreadHelper.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. // set name for this thread.
  46. // NOTE: on *nix string will be trimmed to 16 symbols
  47. void setThreadName(const std::string &name)
  48. {
  49. #ifdef _WIN32
  50. //follows http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  51. const DWORD MS_VC_EXCEPTION=0x406D1388;
  52. #pragma pack(push,8)
  53. typedef struct tagTHREADNAME_INFO
  54. {
  55. DWORD dwType; // Must be 0x1000.
  56. LPCSTR szName; // Pointer to name (in user addr space).
  57. DWORD dwThreadID; // Thread ID (-1=caller thread).
  58. DWORD dwFlags; // Reserved for future use, must be zero.
  59. } THREADNAME_INFO;
  60. #pragma pack(pop)
  61. THREADNAME_INFO info;
  62. info.dwType = 0x1000;
  63. info.szName = name.c_str();
  64. info.dwThreadID = -1;
  65. info.dwFlags = 0;
  66. __try
  67. {
  68. RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
  69. }
  70. __except(EXCEPTION_EXECUTE_HANDLER)
  71. {
  72. }
  73. #else
  74. prctl(PR_SET_NAME, name.c_str(), 0, 0, 0);
  75. #endif
  76. }