线程如何在另一个现有线程的上下文中强制执行函数?
在Delphi/Linux程序中,假设我有两个运行的线程,ThreadA和ThreadB。在某个时间点,线程B需要使ThreadA执行功能并屏蔽,直到函数返回。
在Delphi中,我们有tthread.synchronize可以完成工作,但是只有当线程为主线程时。
有什么想法吗?我使用Delphi,但也欢迎使用C代码的答案。
In a Delphi/Linux program, let's say I have two running threads, ThreadA and ThreadB. At some point in time ThreadB need to make ThreadA execute a function and block until the function returns.
In Delphi, we have TThread.Synchronize which does the work, but only when ThreadA is the main thread.
Any idea? I use Delphi but an answer with C code is also welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为此,线程将必须合作,没有任何机制可以触发跨线的事件。但是,如果您准备实现这样的机制,那就不难做到了,当然可以查看
tthread.synchronize
的源代码以获取提示。从
tthread.syncrhonize
借入借入的来源。您将必须让合作线程作为其主要循环的一部分检查他们的队列 - 当然,这是tthread.synchronize
的工作方式。以下代码基于我们在生产中使用的代码 - 如果单位中未在项目中有评论或参考,则表示歉意。没有提供该函数结果的机制,但是可以通过使用不同的调用模板来解决该功能(因此已知结果类型)。我允许结果
tobject
(即使没有办法知道当前应该是什么),因此可以在需要时返回多值结果。以下内容没有特定于Windows的代码,因此应该按照您的要求在Linux上工作。
您可以继承使用特定调用模板的
tqueuedcallback
的类,这将是确定返回值的一种方法To do this the threads will have to co-operate, there's no mechanism to trigger events across threads. However if you are prepared to implement such a mechanism it's not difficult to do, and of course you can look at the source code for
TThread.Synchronize
for tips.Borrowing from the source for
TThread.Syncrhonize
I have come up with the following. You will have to have the co-operating threads check their queues as part of their main loops - which is of course howTThread.Synchronize
works.The following code is based on code we use in production - my apologies if there are comments or references to items not in the unit. There is no mechanism to provide a result of the function, but that could be resolved with using different calling templates (so the result type is known). I have allowed for a Result
TObject
(even though there's no way to know what that should be currently) so that multi-valued results can be returned if needed.There's no windows specific code in the following, so it should work on Linux as you requested.
You could have inherited classes of
TQueuedCallback
that use a specific calling template, and this would be one way to identify the return value