Other people may feel this way. In the morning, they finish writing a piece of work.Code, The mood is very comfortable, but found an exception, and then start debugging until you forget to eat, a little bit of good mood will be killed. This situation is even more common when writing multi-threaded code. A job thread's tasks are encapsulated layer by layer before being thrown into the job thread queue. I don't know where it comes from, I don't even know where I am. I set the thread name to solve the problem of "Where I am. When debugging, the thread has a name, which improves the efficiency of bug checking.
Set the thread name. There are only a few lines of code. Windows is ready to trigger it. There is no need to write such a simple thing into a blog, but recently I found that many people do not know or did not expect to do so.
The above is nonsense, and the following is the focus:
# Include <iostream> # Include <Windows. h> # Include <Process. h> // 2013.3.5 // Cswuyg // Please refer to the chromium source code: SRC \ base \ threading \ platform_thread_win.cc. // The information on how to set the thread name comes from // A msdn article: Http://msdn2.microsoft.com/en-us/library/xcb2z8hs.aspx Const DWORD kvcthreadnameexception = 0x406d1388 ; 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; // This function has try handling, so it is separated out of its caller. Void Setnameinternal (DWORD thread_id, Const Char * Name ){ // It takes effect only during debugging. If (! : Isdebuggerpresent ()) Return ; Threadname_info Info; Info. dwtype = Zero X 1000 ; Info. szname = Name; Info. dwthreadid = Thread_id; Info. dwflags = 0 ; _ Try {raiseexception (kvcthreadnameexception, 0 ,Sizeof (Info )/ Sizeof (DWORD), reinterpret_cast <dword_ptr *> (& Info); }__ partition T (prediction_continue_execution ){}} Static Unsigned Int _ Stdcall run ( Void * Argv ){ While ( True ) {STD: cout < " Thread " <( Int ) Argv < STD: Endl; sleep ( 5000 );}} Void Testfunc () {DWORD thread_id_1; handle thread_handle_1 = (Handle) _ beginthreadex (null, 0 , Run ,( Void *) 1 , 0 , (Unsigned Int *)&Thread_id_1); setnameinternal (thread_id_1, " My thead thread_1 " ); DWORD thread_id_2; handle thread_handle_2 = (Handle) _ beginthreadex (null, 0 , Run ,( Void *) 2 , 0 , (Unsigned Int *)& Thread_id_2); setnameinternal (thread_id_2, " My thead thread_2 " );} Int Main () {testfunc (); System ( " Pause " ); Return 1 ;}
The code is simple.