Playing TThread inside TThread dervied class

I created a new class derived from the TThread class, and on the constructor I call "inherited Create (True);" and then I call "Resume ()", since I redefine the call to Execute (), now I want to remind Execute () ( Run the thread again) without destroying the instance of the class, so I have a function inside a new class called "myRestart ()" that resembles "inherited Create (True)"; and lets me call "Resume ()" again, and the thread works again.

My question is, is this a safe practice? will it work if i have multiple instances of this class? or is there a better way to do this?

thanks

-1
source share
2 answers

Do not go about this. If you want the procedures / functions in your stream class to run several times, call them from the while () loop in the Execute override and signal the thread to run the code with the appropriate synchronizing object at the top, semaphore or event, they say:

TmyThread.Execute; begin while true do begin someEvent.waitFor(INFINITE); if terminated then exit; doMyProcedure(params); doOtherStuff; end; end; 
+4
source

I think you should show your reboot code? Since, as I know, if a thread completes the Execute procedure, the state in the OS will change to DONE, and the resume call will start this thread again only as a function in the main thread, and not in a separate thread.

since you can use this sample code for your needs

 unit UWorker; interface uses Windows, Classes, Contnrs; type TWorkerThread=class; TWorkerJob=class procedure ExecuteJob(Worker: TWorkerThread); virtual; abstract; end; TWorkerThread=class(TThread) private FFinished: TObjectList; FNotFinished: TObjectList; protected procedure Execute;Override; public constructor Create(createSuspended: Boolean);override; destructor Destroy; override; public property Finished: TObjectList read FFinished; property NotFinished: TObjectList read FNotFinished; end; implementation { TWorkerThread } constructor TWorkerThread.Create(createSuspended: Boolean); begin inherited; FFinished := TObjectList.Create; FNotFinished := TObjectList.Create; end; destructor TWorkerThread.Destroy; begin FFinished.Free; FNotFinished.Free; inherited; end; procedure TWorkerThread.Execute; var CurrentJob: TWorkerJob; begin while not Terminated do begin if FNotFinished.Count > 0 then begin CurrentJob := TWorkerJob(FNotFinished.Items[0]); FNotFinished.Extract(CurrentJob); with CurrentJob do begin ExecuteJob(Self); end; FFinished.Add(CurrentJob); end else begin // pass the cpu to next thread or process Sleep(5); end; end; end; end. 

To use this code, simply create a worker, and then create an instance of the tasks and add them to the NotFinished list. The employee will complete all the tasks one by one. To restart a task, simply extract it from the Ready List and add it again to NotFinished.

remember that you must inherit your tasks and override the ExecuteJob procedure.

-1
source

All Articles