2

我有一个关于德尔福多线程的问题。假设,我有一个线程,我有一个类,它做一些工作并且必须有同步。我怎么能做到?我做这个程序(在 ThreadClass 中):

procedure TThreadClass.SynchProc(P: TProc);
begin
 ...
 Synchronize(TThreadProcedure(P));
 ...
end;

我从我的班级中调用它,在线程中运行,但是......在过程符号“同步”是TThread的一个方法,即对象“(Self as TThread)”,但是当我从我的班级中调用它时,变量“Self”不包含我的 ThreadClass 对象(我不知道,它被包含,可能是第二类的对象,在 Thread 中运行)。分别该程序不起作用。我搜索其他变体(我将我的 threadClass 对象传递给第二类对象并尝试从第二类的过程中调用“同步”过程,但编译器不想编译它)。

你能帮助我吗?将不胜感激任何帮助

来自乌克兰的问候 PS对不起我的英语不好

4

1 回答 1

4

我不是 100% 确定我理解,但我认为你有这样的情况。你有一个TThread后代,比如说TMyThread。而该类又使用另一个名为的类TThreadClass,它不是从TThread. 您想SynchronizeTThreadClass.

以下是一些选项:

  1. TThread将实例传递给TThreadClass. 这是一个相当残酷的解决问题的方法。现在TThreadClass可以对线程做任何事情,而它只想调用Synchronize.
  2. 将引用该Synchronize方法的过程变量传递给TThreadClass. 这使TThreadClass我们能够做它需要做的事情,仅此而已。
  3. 调用TThread.Synchronize传递nil第一个参数的类方法。

其中,最后一个选项是最简单的。你可以这样做:

procedure TThreadClass.SynchProc(P: TThreadProcedure);
begin
  TThread.Synchronize(nil, P);
end;

Note that it is not a good idea to pass in a TProc and cast to TThreadProcedure as per the code in the question. Force the caller to pass in a procedural variable of the right type. In this case the cast is benign, but you should always aim to avoid casts.

于 2013-01-19T13:42:39.557 回答