C++: _beginthreadex, thread function name not showing in Visual Studio Threads window - c++

I recently learnt that ::_beginthreadex() is always preferable to ::CreateThread(), so I changed all my calls that used ::CreateThread().
The only downside is that I no longer see the thread function's name in Visual Studio's Threads window making it hard to quickly identify threads. I assume this was somehow done automatically by the debugger when I used ::CreateThread(), since the parameters are exactly the same, I just changed the name of the function used.
Is there any way to keep using ::_beginthreadex() and to see the thread's name in the Threads window of Visual Studio?

This happens because _beginthreadex() calls CreateThread() with its own thread function that calls the one you specify (so the debugger uses the _threadstartex function name - the one that _beginthreadex() invokes).
You can manually set the thread name yourself using the SetThreadName() example from MSDN. What you might want to do is create your own wrapper for _beginthreadex() that maybe looks something like:
uintptr_t startthreadex(
void* security,
unsigned stacksize,
unsigned (__stdcall * threadproc) (void *),
void* args,
unsigned flags,
unsigned * pThread_id,
char* thread_name)
{
unsigned alt_thread_id;
if (!pThread_id) {
pThread_id = & alt_thread_id;
}
uintptr_t result = _beginthreadex(security, stacksize, threadproc, args, flgas, pThread_id);
if (result == 0) return result;
SetThreadName( *pThread_id, thread_name);
}
Now you can call startthreadex() instead of _beginthreadex() and pass it a thread name. A small advantage to this is that if you use the same function to run several threads, you can easily give them each unique names that reflect the parameters passed ot the thread or whatever.
If you want the thread name to automatically take be the thread proc function name as the debugger's thread name, you could make a wrapper macro that stringizes the function name parameter (all it takes is another level of indirection or to to solve any problem...).
Here's SetThreadName() (it's from http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx):
//
// Usage: SetThreadName (-1, "MainThread");
//
#include <windows.h>
const DWORD MS_VC_EXCEPTION=0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
void SetThreadName( DWORD dwThreadID, char* threadName)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}

There is no particular advantage with using _beginthreadex over CreateThread. The CRT functions would eventually call CreateThread only.
You should read:
Windows threading: _beginthread vs _beginthreadex vs CreateThread C++
http://www.codeguru.com/forum/showthread.php?t=371305
http://social.msdn.microsoft.com/forums/en-US/vclanguage/thread/c727ae29-5a7a-42b6-ad0b-f6b21c1180b2

Related

Create a boost::thread and pass it to a HANDLE

I have the following code:
unsigned long ClassName::fn_StartTesterPresentThread()
{
// m_hTesterPresent is a HANDLE
if (m_hTesterPresent == NULL)
{
DWORD dwThreadId = 0;
m_hTesterPresent = CreateThread(NULL, 0, th_TesterPresent, this, 0, &dwThreadId);
}
return ACTION_SUCCESS;
}
The CreateThread function is Windows-specific, but the code needs to be ported to Linux/non-platform-specific.
I now need a way to create a boost::thread and pass it into the HANDLE m_hTesterPresent.
I was thinking about something like this:
unsigned long Class::fn_StartTesterPresentThread()
{
if (m_hTesterPresent == NULL)
{
DWORD dwThreadId = 0;
boost::thread threadTesterPresent(&m_hTesterPresent);
threadTesterPresent.join();
}
return ACTION_SUCCESS;
}
Is this the correct way? Sadly, I can't yet compile or test because I still have other parts of the project to port.
Furthermore, the project is a DLL and I don't have the client yet that calls the functions in the DLL.
Any help appreciated!
The argument to boost::thread should be a function to call, here th_TesterPresent.
If you are porting this code to non-Windows environments, I suggest you use typedefs to distinguish between the different kinds of HANDLEs.
Then you can have:
#ifndef WINDOWS
typedef boost::thread* THREAD_HANDLE;
typedef boost::mutex MUTEX_HANDLE;
#else
typedef HANDLE THREAD_HANDLE;
typedef HANDLE MUTEX_HANDLE;
#endif
and store THREAD_HANDLE / MUTEX_HANDLE values in various place. Instead of calling OS-specific functions, you can then call generic "createThreadHandle" functions that dispatch to different functions depending on the OS.
Alternatively, you could port your code to an OS-agnostic framework like boost and solve two problems in one go.

Define thread in C++

How do I start a thread using _beginthreadex(), making it execute void myFunction(wchar_t *param);? I try to use this:
_beginthread(NULL, 0, myFunction, L"someParam", 0, &ThreadID);
but there is compilation error:
error C2664: 'beginthreadex' : cannot convert parameter 3 from 'void (_cdecl *)(wchar_t *)' to 'unsigned int (__stdcall *)(void *)'.
How I can resolve this error? I seem able to do _beginthread((void(*)(void*))myFunction, 0 , (void *)L"someParam");. But for _beginthreadex() these casts don't seem to work. What do
I need to do?
This code doesn't output anything. What's wrong?
unsigned int __stdcall myFunction( void *someParam )
{
printf("Hello world!");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
_beginthreadex(NULL, 0, myFunction, L"param", 0, NULL);
return 0;
}
_beginthreadex requires a function that uses the __stdcall calling convention, not the __cdecl calling convention, which is the default. To fix it, declare your thread procedure with the __stdcall calling convention:
unsigned int __stdcall myFunction(void *arg)
{
...
}
Do NOT cast the function pointer you're passing into _beginthread or _beginthreadex: a function pointer cast is a bug waiting to happen.
Function prototype requirements for each Microsoft CRT thread launch functions are:
_beginthread: void __cdecl procname(void * arg);
_beginthreadex: unsigned int __stdcall procname(void *arg);
You should also be aware of the differences between the two.
_beginthread: allocates a new thread and invokes the thread procedure passed as the argument. Using this API the thread-creation parameters are somewhat limited. The return value of this function is a uintptr_t, but is actually a Windows thread handle of type HANDLE. It must be cast to a HANDLE variable to be used in such functions as WaitForSingleObject, etc. When the thread procedure finishes through normal function-exit the thread handle is automatically closed for you by the runtime. This is important. Although this function returns a thread handle just like _beginthreadex, it is conceivable for the thread to start and finish before you can do anything with the handle (such as a wait, suspend, etc.). Once the thread procedure finishes the RT will close the handle, and therefore your local variable holding the initial returned handle is now invalid.
_beginthreadex: allocates a new thread and invokes the thread procedure passed as the argument. This version allows significantly more control over how the thread is created, including the stack size, initial suspended state, etc. The return value of this function is a uintptr_t, but is actually a Windows thread handle of type HANDLE. It must be cast to a HANDLE variable to be used in such functions as WaitForSingleObject, etc. When the thread procedure finishes through normal function-exit the thread handle is NOT automatically closed for you by the runtime. You are responsible for closing the thread handle returned by this function, and should do so as soon as it is no longer needed.
Which to use: Use _beginthread if you have no need for the thread handle to be used in Wait functions and such, and have no special thread-creation needs (like creating a thread with an initially-suspended state). Use _beginthreadex when you need a wait'able thread handle, finer control over the creation parameters, etc.
EDIT: Sample for the OP
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <process.h>
unsigned int __stdcall MyThread(void *p)
{
_tprintf(_T("%s\n"), p);
_tprintf(_T("Thread finishing!\n"));
return 0;
}
int _tmain(int argc, TCHAR *argv[])
{
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, MyThread, _T("Hello, World!"), 0, NULL);
if (hThread != INVALID_HANDLE_VALUE)
{
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
_tprintf(_T("Thread finished!\n"));
}
return 0;
}
As in the other answer above, don't forget to wait for your thread to finish before _tmain exits, or you likely will see no output.

std::thread - naming your thread

The new C++ has this std::thread type. Works like a charm.
Now I would like to give each thread a name for more easy debugging (like java allows you to).
With pthreads I would do:
pthread_setname_np(pthread_self(), "thread_name");
but how can I do this with c++0x?
I know it uses pthreads underneath on Linux systems, but I would like to make my application portable. Is it possible at all?
A portable way to do this is to maintain a map of names, keyed by the thread's ID, obtained from thread::get_id(). Alternatively, as suggested in the comments, you could use a thread_local variable, if you only need to access the name from within the thread.
If you didn't need portability, then you could get the underlying pthread_t from thread::native_handle() and do whatever platform-specific shenanigans you like with that. Be aware that the _np on the thread naming functions means "not posix", so they aren't guaranteed to be available on all pthreads implementations.
An attempt at making a wrapper to deal with many Linuxes as well as Windows. Please edit as needed.
#ifdef _WIN32
#include <windows.h>
const DWORD MS_VC_EXCEPTION=0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
void SetThreadName(uint32_t dwThreadID, const char* threadName)
{
// DWORD dwThreadID = ::GetThreadId( static_cast<HANDLE>( t.native_handle() ) );
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}
void SetThreadName( const char* threadName)
{
SetThreadName(GetCurrentThreadId(),threadName);
}
void SetThreadName( std::thread* thread, const char* threadName)
{
DWORD threadId = ::GetThreadId( static_cast<HANDLE>( thread->native_handle() ) );
SetThreadName(threadId,threadName);
}
#elif defined(__linux__)
#include <sys/prctl.h>
void SetThreadName( const char* threadName)
{
prctl(PR_SET_NAME,threadName,0,0,0);
}
#else
void SetThreadName(std::thread* thread, const char* threadName)
{
auto handle = thread->native_handle();
pthread_setname_np(handle,threadName);
}
#endif
You can use std::thread::native_handle to get the underlaying implementation defined thread. There is no standard function for that natively.
You can find an example here.
For windows [debugger], you can easily use the "normal" method;
http://msdn.microsoft.com/en-gb/library/xcb2z8hs.aspx
Just need the thread id which you can obtain via
#include <windows.h>
DWORD ThreadId = ::GetThreadId( static_cast<HANDLE>( mThread.native_handle() ) );
I've both seen this done in a system predating c++11 (where we basically invented our own Thread class that was very similar to std::thread) and in one I wrote fairly recently.
Basically, the pool really puts std::thread 2 layers down- you have a PoolThread class that contains a std::thread plus metadata like its name, ID, etc. and the the control structure that links it to its controlling pool, and the ThreadPool itself. You want to use thread pools in most threaded code for several reasons:
1) You can hide all the explicit "detach", "join", start thread on std::thread construction, etc. from users. That produces MUCH safer & cleaner code.
2) Better resource management: Too many threads will cripple performance even more than having too few. A well-built pool can do advanced things like automatic load balancing and cleaning-up hung or deadlocked threads.
3) Thread reuse: std::thread by itself is easiest to use by running every parallel task on its own thread. But thread creation & destruction are expensive, and can easily swamp the speed boost from parallel processing if you're not careful. So, it usually makes more sense to have pool threads that pull work tasks from a queue and only exit after receiving some signal.
4) Error handling: std::thread is just an execution context. If the task you're running on it throws an un-handled exception or std::thread ITSELF fails, the process will just crash right there. To do fault-tolerant multithreading, you need a Pool or something similar that can quickly catch such things and at least emit meaningful error messages before the process dies.
In header file do:
const std::string & ThreadName(const std::string name="");
In src file do:
const std::string & ThreadName(const std::string name)
{
static std::atomic_int threadCount{0};
const thread_local std::string _name = name + std::to_string(threadCount.fetch_add(1));
return _name;
}
Usage:
void myThread()
{
ThreadName("myThread"); // Call once at very beginning of your thread creation
...
std::cout << ThreadName() << std::endl; // Anyplace in your code
}

Can I get a "__try"-clause to compile with /EHsc?

The Microsoft-approved way of setting a thread name doesn't compile with /EHsc enabled. The compiler tells me
C2712: Cannot use __try in functions that require object unwinding
http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
//
// Usage: SetThreadName (-1, "MainThread");
//
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // must be 0x1000
LPCSTR szName; // pointer to name (in user addr space)
DWORD dwThreadID; // thread ID (-1=caller thread)
DWORD dwFlags; // reserved for future use, must be zero
} THREADNAME_INFO;
void SetThreadName( DWORD dwThreadID, LPCSTR szThreadName)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = szThreadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException( 0x406D1388, 0, sizeof(info)/sizeof(DWORD), (DWORD*)&info );
}
__except(EXCEPTION_CONTINUE_EXECUTION)
{
}
}
Any idea on how to fix this without changing the compiler settings?
Using Visual Studio 2008 on WinXP
The usual solution is to separate it into two functions, one calling the other. One sets up the SEH __try/__except block and the other has all the stuff related to C++ exceptions and destructor calls for local variables.
But I don't see any types that need a destructor call.
Maybe it's just a typo (except) vs (__except)?

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.
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).
Use SetThreadName
Windows 10 added SetThreadDescription(), on that platform this will be the best method.