multithreading 获取当前正在执行的线程的 TThread 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/155560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:58:44  来源:igfitidea点击:

Get the TThread object for the currently executing thread?

multithreadingdelphi

提问by Barry Kelly

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.

我想要一个像 GetCurrentThread 这样的函数,它返回当前执行线程的 TThread 对象。我知道有一个 Win32 API 调用 GetCurrentThread,但它返回线程 ID。如果有可能从该 ID 获取 TThread 对象,那也很好。

回答by Hugh Allen

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.

尽管如果它是由工作线程加载的,那么这将无法从使用 Delphi 创建的 DLL 中工作。

回答by Barry Kelly

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

Delphi 的最新版本 Delphi 2009 在 TThread 类上有一个 CurrentThread 类属性。

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.

如果它是本机线程,这将返回正确的 Delphi 线程对象。如果该线程是一个“外来”线程,即使用其他机制创建或在第三方线程的回调上创建,那么它将围绕线程句柄创建一个包装线程。

回答by gabr

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

我正在使用我自己的 TThread 后代,它在全局列表中注册自己,用锁保护。

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

这样,此后代中的方法可以遍历列表并获取 TThread 并给出 ID。

回答by gabr

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.

回答我自己的问题。我想从 ID 中获取 TThread 对象是不可能的。可以通过使用全局变量。然后比较它的句柄和当前线程id,就可以确定是否在主线程中运行。

回答by mwore

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

当前正在执行的线程不是您试图从中运行函数的线程吗?

回答by Ates Goral

You could store the pointer of the TThread instance in the current thread's context via the TlsSetValueAPI 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 currentthread.

您可以通过TlsSetValueAPI 调用将 TThread 实例的指针存储在当前线程的上下文中,然后使用TlsGetValue检索它。但是,请注意,这仅在您尝试检索/存储当前线程的 TThread 实例时才有效。