How run method in parent thread context?

Viewed 223

If I want call event from thread, I use Synchronize(or Queue) method, then event is called in main thread. What if I want run event in other thread, but not main one? I wrote little example here:

---Inner thread ---

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;

---Outer thread---

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;

---Usage---

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

Outer thread run few iner threads and wait some time. After this he check if all notified success.

Question is: how run event in inner thread (_onSucces) in outer thread context?

I found TIdSync but it seems to be used in indy.

0 Answers
Related