GetThreadName

Retrieves the name that was assigned to a thread using SetThreadName.

Syntax

BOOL GetThreadName(
         HANDLE hThread,
         PWSTR lpThreadName,
         SIZE_T nBufferLength,
         SIZE_T *pnRequiredLength
)  

Parameters

hThread
Type: HANDLE 

[in] A HANDLE for the thread to retrieve the name of.

lpThreadName
Type: PWSTR 

[out] A buffer that will contain the name of the thread upon return.

nBufferLength
Type: SIZE_T 

[in] The size of the buffer supplied in lpThreadName.

pnRequiredLength
Type: SIZE_T *

[out] The size of the buffer required to hold the thread name. If this value is larger than nBufferLength, GetThreadName must be called again with a larger buffer.

Return value

Type: BOOL 

Indicates whether the thread’s name was successfully retrieved. The function returns TRUE if the name was retrieved and FALSE otherwise. If FALSE is returned use GetLastError to get the specific error code. An error code of ERROR_INSUFFICIENT_BUFFER indicates that the buffer that was passed in was not large enough to hold the name of the thread.

Remarks

A thread’s name can change at any time. For example, a different thread may be changing a thread’s name while you’re trying to retrieve it. It is recommended that GetThreadName be called in a loop until the size of the buffer that is passed in is large enough to hold the thread name.

Example

std::vector<WCHAR> buffer; 
buffer.resize(64, 0); 

// 
// Thread names can change at any point, so loop until the buffer is large enough, or           // error (out of memory), 
// or no name, which is just another case of buffer is large enough. 
// 
while (true) 
{ 
    SIZE_T size; 
    success = GetThreadName(GetCurrentThread(), &buffer[0], buffer.size(), &size); 
    assert(size != buffer.size()); 

    if (success) 
    { 
        assert(size < buffer.size()); 
        buffer.resize(size + 1); // add one for a terminator 
        break; 
    } 

    DWORD error = GetLastError(); 
    if (error != ERROR_INSUFFICIENT_BUFFER) 
    { 
        buffer.resize(1); 
        buffer[0] = 0; 
        break; 
    } 
    assert(size > buffer.size()); 
    // the buffer passed in wasn’t large enough.  Resize and try again 
    buffer.resize(size);     
} 

// buffer now contains the thread name  

Requirements

Header: Declared in minwinbase.h.

Library: Use toolhelpx.lib.