Delphi named topics - why?

When you create a TThread child using the tool palette in your BDS, you can specify a name for the thread. Here is the automatically generated code. You simply call the SetName () function in the Execute method, and the thread calling this method is given a name in some strange way ...

{$IFDEF MSWINDOWS} type TThreadNameInfo = record FType: LongWord; // must be 0x1000 FName: PChar; // pointer to name (in user address space) FThreadID: LongWord; // thread ID (-1 indicates caller thread) FFlags: LongWord; // reserved for future use, must be zero end; {$ENDIF} { TTestThread } procedure TTestThread.SetName; {$IFDEF MSWINDOWS} var ThreadNameInfo: TThreadNameInfo; {$ENDIF} begin {$IFDEF MSWINDOWS} ThreadNameInfo.FType := $1000; ThreadNameInfo.FName := 'ThreadName'; ThreadNameInfo.FThreadID := $FFFFFFFF; ThreadNameInfo.FFlags := 0; try RaiseException( $406D1388, 0, sizeof(ThreadNameInfo) div sizeof(LongWord), @ThreadNameInfo ); except end; {$ENDIF} end; 

I believe this is really useful when debugging, since you can see not only the TID, but also the thread names assigned in this way. You know which stream is due to this.

Please tell me, however, if the assigned name can be obtained in any way. Can it be read based on the stream descriptor? Or can it be read even from an β€œexternal” process by another process? You know, there are applications that list the processes and threads running in them. Will this name be available for such applications?

Thanks!

+6
source share
2 answers

In fact, thread names are used for debugging purposes only and nothing at all. In your code, you can simply define threads using ThreadID. And if you want to keep the name with these stream identifiers, save a separate (dictionary) list that maps each stream identifier to whatever name you like.
The hack you see does an unpleasant trick. The thrown exception is caught by the debugger, which simply treats it as a special exception and will simply continue to execute. The exception flag simply tells the system to continue working after an exception occurs because the code will process it. An empty exception-exception handles the exception inside your code. This is just a dirty trick for communicating with the debugger, which will eliminate the exception and remember the name you just passed it ...

+9
source

This is a fully debugging feature. In fact, the thread object does not even keep track of its name. It sends it directly to the debugger, but does not save a copy of the name for itself. It is not accessible from your own program or from anywhere other than the debugger.

+6
source

All Articles