Serkan
Serkan

Reputation:

Get the TThread object for the currently executing thread?

I want a function like GetCurrentThread which returns a TThread object of the current executing thread. I know there is a Win32 API call GetCurrentThread, but it returns the thread Id. If there is a possibility to get TThread object from that ID that's also fine.

Upvotes: 17

Views: 24032

Answers (6)

gabr
gabr

Reputation: 26850

I'm using my own TThread descendent that registers itself in a global list, protected with a lock.

That way, a method in this descendent can walk the list and get a TThread give an ID.

Upvotes: 4

Barry Kelly
Barry Kelly

Reputation: 42182

The latest version of Delphi, Delphi 2009, has a CurrentThread class property on the TThread class.

This will return the proper Delphi thread object if it's a native thread. If the thread is an "alien" thread, i.e. created using some other mechanism or on a callback from a third party thread, then it will create a wrapper thread around the thread handle.

Upvotes: 23

Hugh Allen
Hugh Allen

Reputation: 6695

From your own answer, it seems maybe you only want to "determine if running in the main thread or not", in which case you can just use

if Windows.GetCurrentThreadId() = System.MainThreadID then
// ...

Although this won't work from a DLL created with Delphi if it was loaded by a worker thread.

Upvotes: 25

Ateş Göral
Ateş Göral

Reputation: 140162

You could store the pointer of the TThread instance in the current thread's context via the TlsSetValue API call and then retrieve it using TlsGetValue. However, note that this will only work if you're trying to retrieve/store the TThread instance of the current thread.

Upvotes: 0

mwore
mwore

Reputation: 476

Wouldn't the current executing thread be the one you're trying to run a function from?

Upvotes: 0

Serkan
Serkan

Reputation:

Answering my own question. I guess it is not possible to get TThread object from ID. It is possible by using a global variable. Then comparing its handle and current thread id, one can determine if running in the main thread or not.

Upvotes: 0

Related Questions