How to run a method in the context of the parent thread?

If I want to trigger an event from a thread, I use the Synchronize (or Queue) method, then the event is called on the main thread. What if I want to fire the event in another thread, but not in the main one? I wrote a small 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;

--- External 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;

The outer thread starts several iner threads and waits for a while. After that, he checks to see if there are any confirmed successes.

Question: how to start an event in an internal thread (_onSucces) in an external thread context?

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

+4
source share

Source: https://habr.com/ru/post/1677189/


All Articles