Windows Thread Names

    This site uses cookies. By continuing to browse this site, you are agreeing to our Cookie Policy.

    • Windows Thread Names

      While i was working with threads in VC++ i saw that in the thread list each thread has name field.

      And every Thread was named Win32 Thread. Some how that annoyed me alot and i found a solution to give threads names.

      Here the code to name a thread. This code was taken from MSDN and i suggest only to use it in debug builds.


      Source Code

      1. typedef struct tagTHREADNAME_INFO
      2. {
      3. DWORD dwType; // must be 0x1000
      4. LPCSTR szName; // pointer to name (in user addr space)
      5. DWORD dwThreadID; // thread ID (-1=caller thread)
      6. DWORD dwFlags; // reserved for future use, must be zero
      7. } THREADNAME_INFO;
      8. void SetThreadName( DWORD dwThreadID, LPCSTR szThreadName)
      9. {
      10. THREADNAME_INFO info;
      11. info.dwType = 0x1000;
      12. info.szName = szThreadName;
      13. info.dwThreadID = dwThreadID;
      14. info.dwFlags = 0;
      15. __try
      16. {
      17. RaiseException( 0x406D1388, 0, sizeof(info)/sizeof(DWORD), (DWORD*)&info );
      18. }__except (EXCEPTION_CONTINUE_EXECUTION)
      19. {
      20. }
      21. }
      Display All


      Now with SetThreadName you can name your thread. But to do so you need the thread Id to make this.

      On Windows Xp there is no way to get the thread id with out running the thread and call GetCurrentThreadID

      So here the solution to solve this.

      Source Code

      1. struct ThreadInfo_t
      2. {
      3. ThreadInfo_t()
      4. {
      5. run = 0;
      6. nThreadId = 0;
      7. }
      8. IRunnable *run;
      9. u32 nThreadId;
      10. std::string strThreadName;
      11. };
      Display All


      You will pass this Struct to the thread entry point which looks like this.

      Source Code

      1. DWORD WINAPI ThreadEntry (void *pArg)
      2. {
      3. ThreadInfo_t *info = reinterpret_cast<ThreadInfo_t*>( pArg );
      4. info->nThreadId = GetCurrentThreadId();
      5. // set the thread name only in debug build
      6. #ifdef _DEBUG
      7. SetThreadName(info->nThreadId,info->strThreadName.c_str());
      8. #endif
      9. info->run->Run();
      10. return 0;
      11. }
      Display All
      Files
      • threads.png

        (23.54 kB, downloaded 1,101 times, last: )