如何在父线程上下文中运行方法?

时间:2017-05-15 16:15:38

标签: multithreading delphi

如果我想从线程调用事件,我使用Synchronize(或Queue)方法,然后在主线程中调用event。如果我想在其他线程中运行事件但不是主线程怎么办? 我在这里写了一些例子:

---内线---

procedure TInnerThread.Execute;
var
    number: Integer;
begin
    while not TThread.CheckTerminated do
    begin
        Sleep(100);
        number := Random(5);
        if number = 3 then
        begin
            Synchronize(RunOnSuccess);
            Exit;
        end;
    end;
end;

procedure TInnerThread.RunOnSuccess;
begin
    _onSucces();
end;

---外线---

procedure TOuterThread.Execute;
const
    THREADS = 5;
var
    tasks: TList<TInnerThread>;
    i: Integer;
    successes: Integer;
begin
    successes := 0;
    tasks := TList<TInnerThread>.Create;
    for i := 0 to THREADS - 1 do
    begin
        tasks.Add(TInnerThread.Create(true));
        tasks[i].OnSucces := procedure
            begin
                Inc(successes);
            end;
    end;

    for i := 0 to THREADS - 1 do
    begin
        tasks[i].Start;
    end;

    sleep(3000);

    for i := 0 to THREADS - 1 do
    begin
        tasks[i].Terminate;
    end;

    if successes = THREADS then
        Synchronize(RunOnBigSuccess)
end;

procedure TOuterThread.RunOnBigSuccess;
begin
    _onBigSuccess();
end;

--- ---用法

    LHCAnalysis := TOuterThread.Create(true);
    LHCAnalysis.OnBigSuccess := procedure
        begin
            ShowMessage('Higgs boson discovered!');
        end;
    LHCAnalysis.Start;

外线程运行几个iner线程并等待一段时间。在此之后,他检查是否所有通知成功。

问题是:外线程上下文中如何在内部线程(_onSucces)中运行事件?

我找到了TIdSync,但它似乎在indy中使用。

0 个答案:

没有答案