2
0

CThreadHelper.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include "StdInc.h"
  2. #include "CThreadHelper.h"
  3. #ifdef VCMI_WINDOWS
  4. #include <windows.h>
  5. #elif !defined(VCMI_APPLE)
  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<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. for(int i=0;i<threads;i++)
  27. grupa.create_thread(std::bind(&CThreadHelper::processTasks,this));
  28. grupa.join_all();
  29. }
  30. void CThreadHelper::processTasks()
  31. {
  32. while(true)
  33. {
  34. int pom;
  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 VCMI_WINDOWS
  50. #ifndef __GNUC__
  51. //follows http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  52. const DWORD MS_VC_EXCEPTION=0x406D1388;
  53. #pragma pack(push,8)
  54. typedef struct tagTHREADNAME_INFO
  55. {
  56. DWORD dwType; // Must be 0x1000.
  57. LPCSTR szName; // Pointer to name (in user addr space).
  58. DWORD dwThreadID; // Thread ID (-1=caller thread).
  59. DWORD dwFlags; // Reserved for future use, must be zero.
  60. } THREADNAME_INFO;
  61. #pragma pack(pop)
  62. THREADNAME_INFO info;
  63. info.dwType = 0x1000;
  64. info.szName = name.c_str();
  65. info.dwThreadID = -1;
  66. info.dwFlags = 0;
  67. __try
  68. {
  69. RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
  70. }
  71. __except(EXCEPTION_EXECUTE_HANDLER)
  72. {
  73. }
  74. #else
  75. //not supported
  76. #endif
  77. #elif defined(__linux__)
  78. prctl(PR_SET_NAME, name.c_str(), 0, 0, 0);
  79. #endif
  80. }