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
1.2k views
in Technique[技术] by (71.8m points)

multithreading - Named threads in Delphi - what is that for?

When you create a TThread descendant using the tool palette in your BDS, you can provide a name for the thread. Here's the auto-generated code. You just call the SetName() function in the Execute method and the thread calling this method is given a name in a kind of weird 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 find it really useful during debugging for you can see not only TIDs, but also thread names assigned that way. You know which thread is which thanks to that.

Please tell me, however, if the name assigned can be accessed in any way. Can it be read based on a thread's handle? Or can it be read even from 'outside' the process by another process? You know, there are applications which list your processes and the threads working in them. Will this name be accessible to apps like that?

Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Actually, thread names are just used for debugging purposes and nothing else, really. In your code, you could just identify threads by using the ThreadID. And if you want to keep a name with those thread ID's, keep a separate (dictionary) list which maps each thread ID to whatever name you like.
The hack that you see does a nasty trick. The exception that is raised is captured by the debugger, which just handles it as a special exception and will just continue execution. The exception flag just tells the system to continue after the exception is raised, since the code will handle it. The empty except-clause is handling the exception within your code. It's just a dirty trick to communicate with the debugger, which will zee the exception and remember the name you've just passed to it...


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

...