Pages

Thursday, May 5, 2011

Naming threads

In multithreaded applications it is often useful to distinct threads in the Threads window. If you, say, develop file downloader, you will definitely start each downloading in a separate thread, and when you break Visual Studio debugger, you will need to be able to distinct what each thread is doing now. Default thread names will not tell you anything meaningful, especially if you have dozens of threads created by _beginthreadex:
1
There is a trick specific to VS debugger only that allows changing thread name at runtime so that instead of meaningless _threadstartex you can name a thread with its state for example:
2
And the trick looks like the following below:
void SetThreadName(
    const char* threadName, 
    DWORD dwThreadID = GetCurrentThreadId())
{
    __try
    {
        struct 
        {
           DWORD type;          // Must be 0x1000.
           const char* name;    // Pointer to name (in user addr space).
           DWORD tid;           // Thread ID (-1=caller thread).
           DWORD reserved;      // Reserved for future use, must be zero.

        } 
        info = 
        { 
            0x1000, 
            threadName, 
            dwThreadID, 
            0 
        };

        const DWORD MS_VC_EXCEPTION = 0x406D1388;

        RaiseException(
            MS_VC_EXCEPTION, 
            0, 
            sizeof(info)/sizeof(ULONG_PTR), 
            reinterpret_cast<ULONG_PTR*>(&info));
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    { 
        // Do nothing.
    }
}

unsigned __stdcall  ThreadProc(void *)
{
    ...
    SetThreadName("Workflow 'Registration'");
    ...
}

Thanks. AS-IS ;)

No comments:

Post a Comment