There is code for threads. And the creation of multiple threads with different input parameters. How to define each thread its local variables?
Now I do it as follows:

ThreadDead = class(TThread) protected procedure Execute; override; public constructor Create(startnum: integer; step: integer; endnum: integer); end; var th1, th2: ThreadDead; mut: THandle; ThreadVar sn, stp, en: integer; constructor ThreadDead.Create(startnum, step, endnum: integer); begin inherited Create(false); FreeOnTerminate:=True; sn:=startnum; stp:=step; en:=endnum; end; procedure ThreadDead.Execute; begin while sn<en do begin WaitForSingleObject(mut,infinite); form1.out.Lines.Add(inttostr(sn)); sn:=sn+stp; ReleaseMutex(mut); end; end; procedure TForm1.FormCreate(Sender: TObject); begin mut:=CreateMutex(nil,false,''); th1:=ThreadDead.Create(0, 2, 100); th2:=ThreadDead.Create(1, 2, 100); th1.Execute; th2.Execute; end; 

As a result, the output is the following: 1, 3, 5, ..., 95, 97, 99.
Please help solve the problem.
Expected output: 0, 1, 2, ..., 97, 98, 99.

  • one
    Make them members of the thread class. - Slava Zhuyko
  • @SlavaZhuyko There is not only that :) Another call to the VCL from the stream and an extra call to Thread.Execute. - kami
  • @SlavaZhuyko, did as you indicated - now all numbers are displayed. Only streams work first one, then the other. Is this because of a small number of iterations or is I using mutex incorrectly? Made a delay between iterations - no change. - SaheR
  • @kami, in this program, stream access to VCL is not critical, but from now on I will be more careful with such actions. In inherited Create(false); the value has changed, now Execute seems to be justified. - SaheR
  • one
    An external call to execute is never justified. This method starts automatically when the thread starts. Actually, this is the "flow" with tz. Delphi and he will be called on his own. And about the "not critical" - never say so when working with VCL <-> stream. Only via Synchronize, Queue, Post / SendMessage. By the way, nobody guarantees you the sequence of actions of the two flows, incl. and mutex. Is that on systems to Win Vista. - kami

1 answer 1

sn, stp, en: integer; move to the private section of the flow class - each flow will have its own local variables.
CloseHandle(mut); remove away from creating threads (removed in the FormDestroy method) - otherwise the threads do not have time to work out - the absence of mutex does not allow.
The output of information on the form to put in a separate method flow and call it (method) via Synchronize Synchronize(outAdd);

 procedure ThreadDead.outAdd; begin form1.out.Lines.Add(inttostr(sn)); end; 

otherwise, the form becomes inaccessible while the threads are outputting. In addition, the output may be incorrect.