SetThreadName not working with Visual Studio 2005

2019-03-04 08:28发布

问题:

SetThreadName does not set thread name with Visual Studio 2005, when used as below:

DWORD threadId;
HANDLE handle = CreateThread(NULL, stackSize, ThreadFunction,
                             ThreadParam, CREATE_SUSPENDED, &threadId);
if (handle)
{

   SetThreadName(threadId, "NiceName");
   ResumeThread(handle);
}

After opening the Threads window, instead of NiceName I can see the name of the ThreadFunction there. Other tools (like Intel Parallel Inspector) use NiceName as expected.

  • Is something wrong with the code above?

  • Does the code work with Visual Studio 2008 or 2010 editions?

回答1:

After a few experiments I have found it is because the Visual Studio is trying to be smart and when the thread begins to execute it gives a name to itself. The workaround is not to try to give the name to thread before the thread has actually started, the easiest way how to achieve this is to call the SetThreadName from inside of the thread function.

Still I would be interested in knowing if other versions of Visual Studio show the same behaviour.