views:

2460

answers:

6

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.

A: 

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.

Delphi 2009, at least, has a TThread.CurrentThread property.
Barry Kelly
A: 

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

mwore
A: 

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.

Ates Goral
+4  A: 

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.

Hugh Allen
+11  A: 

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.

Barry Kelly
Unfortunately, CurrentThread has a serious flaw rendering it useless: http://stackoverflow.com/questions/188281/delphi-tthread-currentthread-and-eaccessviolation-is-this-a-bug-or-my-incompete
Roddy
+2  A: 

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.

gabr