SuperBug
SuperBug

Reputation: 67

Delphi firemonkey android multithreading

I tried to make multiworker thread for a android platform using delphi firemonkey using method from this multithread

it didn't work, is there any way to create worker thread like that?

Thanks.

Upvotes: 2

Views: 5895

Answers (1)

Peter-John Jansen
Peter-John Jansen

Reputation: 643

You can make use of the Parallel Programming Library, using Tasks that create threads here is a quick example

uses: System.Threading
var
    Mythreadtask : ITask;

procedure createthreads;
begin
    if Assigned(Mythreadtask) then
    begin
        if Mythreadtask.Status = TTaskStatus.Running then
        begin
        //If it is already running don't start it again
            Exit;
        end;
    end;
    Mythreadtask := TTask.Create (procedure ()
    var s : String //Create Thread var here
    begin
    //Do all logic in here
    //If you need to do any UI related modifications
     TThread.Synchronize(TThread.CurrentThread,procedure()
        begin 
            //Remeber to wrap them inside a Syncronize
        end);
    end);
// Ensure that objects hold no references to other objects so that they can be freed, to avoid memory leaks. 
end;

Add:

If you want to like in your comment want 5 worker threads you can make use of a array of tasks, this is extracted from the Parallel Programming Library Documentation

procedure createthreads;
var 
    tasks: array of ITask; //Declare your dynamic array of ITask 
    value: Integer; 
begin 
Setlength (tasks ,2); // Set the size of the Array (How many threads you want to use in your case this would be 5)
value := 0; 

//This the 1st thread because it is the thread located in position 1 of the array of tasks
tasks[0] := TTask.Create (procedure () 
begin 
    sleep (3000); // 3 seconds 
    TInterlocked.Add (value, 3000); 
 end); 
 tasks[0].Start;// until .Start is called your task is not executed
 // this starts the thread that is located in the position [0] of tasks 

 //And this is the 2nd thread 
 tasks[1] := TTask.Create (procedure () 
 begin 
     sleep (5000); // 5 seconds 
     TInterlocked.Add (value, 5000);
 end); 
 tasks[1].Start;// and the second thread is started 
 TTask.WaitForAll(tasks); {This will have the mainthread wait for all the 
                 {threads of tasks to finish before moving making sure that when the
                 showmessage All done is displayed all the threads are done} 
 ShowMessage ('All done: ' + value.ToString); 
 end;

Upvotes: 6

Related Questions