Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

c++ - How to change the name of a thread

I have a server application that uses "a lot" of threads. Without wanting to get into an argument about how many threads it really should be using, it would be nice to be able to see some descriptive text in the debugger "threads" window describing what each one is, without having to click through to it and determine from the context what it is.

They all have the same start address so generally the threads window says something like "thread_base::start" or something similar. I'd like to know if there is an API call or something that allows me to customise that text.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the code I use.

This goes in a header file.

#pragma once

#define MS_VC_EXCEPTION 0x406d1388
#pragma warning(disable: 6312)
#pragma warning(disable: 6322)

typedef struct tagTHREADNAME_INFO
{
    DWORD dwType;        // must be 0x1000
    LPCSTR szName;       // pointer to name (in same addr space)
    DWORD dwThreadID;    // thread ID (-1 caller thread)
    DWORD dwFlags;       // reserved for future use, most be zero
} THREADNAME_INFO;

inline
void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName)
{
#ifdef _DEBUG
    THREADNAME_INFO info;
    info.dwType = 0x1000;
    info.szName = szThreadName;
    info.dwThreadID = dwThreadID;
    info.dwFlags = 0;

    __try
    {
        RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(DWORD), (DWORD *)&info);
    }
    __except (EXCEPTION_CONTINUE_EXECUTION)
    {
    }
#else
    dwThreadID;
    szThreadName;
#endif
}

Then I call it like this inside the threads proc.

SetThreadName(GetCurrentThreadId(), "VideoSource Thread");

It is worth noting that this is the exact code that David posted a link to (Thanks! I had forgotten where I got it). I didn't delete this post because I'd like the code to still be available if MSDN decides to reorganize its links (again).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...