CThreadHelper.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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_HAIKU)
  15. #include <OS.h>
  16. #elif !defined(VCMI_APPLE) && !defined(VCMI_FREEBSD) && \
  17. !defined(VCMI_HURD) && !defined(VCMI_OPENBSD)
  18. #include <sys/prctl.h>
  19. #endif
  20. VCMI_LIB_NAMESPACE_BEGIN
  21. static thread_local std::string threadNameForLogging;
  22. std::string getThreadName()
  23. {
  24. if (!threadNameForLogging.empty())
  25. return threadNameForLogging;
  26. return boost::lexical_cast<std::string>(std::this_thread::get_id());
  27. }
  28. void setThreadNameLoggingOnly(const std::string &name)
  29. {
  30. threadNameForLogging = name;
  31. }
  32. void setThreadName(const std::string &name)
  33. {
  34. threadNameForLogging = name;
  35. #ifdef VCMI_WINDOWS
  36. #ifndef __GNUC__
  37. //follows http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  38. const DWORD MS_VC_EXCEPTION=0x406D1388;
  39. #pragma pack(push,8)
  40. typedef struct tagTHREADNAME_INFO
  41. {
  42. DWORD dwType; // Must be 0x1000.
  43. LPCSTR szName; // Pointer to name (in user addr space).
  44. DWORD dwThreadID; // Thread ID (-1=caller thread).
  45. DWORD dwFlags; // Reserved for future use, must be zero.
  46. } THREADNAME_INFO;
  47. #pragma pack(pop)
  48. THREADNAME_INFO info;
  49. info.dwType = 0x1000;
  50. info.szName = name.c_str();
  51. info.dwThreadID = -1;
  52. info.dwFlags = 0;
  53. __try
  54. {
  55. RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
  56. }
  57. __except(EXCEPTION_EXECUTE_HANDLER)
  58. {
  59. }
  60. #else
  61. //not supported
  62. #endif
  63. #elif defined(VCMI_APPLE)
  64. pthread_setname_np(name.c_str());
  65. #elif defined(VCMI_FREEBSD)
  66. pthread_setname_np(pthread_self(), name.c_str());
  67. #elif defined(VCMI_HAIKU)
  68. rename_thread(find_thread(NULL), name.c_str());
  69. #elif defined(VCMI_UNIX)
  70. prctl(PR_SET_NAME, name.c_str(), 0, 0, 0);
  71. #else
  72. #error "Failed to find method to set thread name on this system. Please provide one (or disable this line if you just want code to compile)"
  73. #endif
  74. }
  75. VCMI_LIB_NAMESPACE_END