L
L
libera2016-01-24 17:28:49
Delphi
libera, 2016-01-24 17:28:49

Multithreaded program?

For 2 days now I can not figure out how to do it.
Tell
me I'm calling the flow

procedure TForm1.btn1Click(Sender: TObject);
var
  I: Integer;
begin
for I := 0 to se1.Value do
  text:=proba.Create(False);
  text.Priority:=tpNormal;
end;
 
end.

in the stream
procedure Proba.Execute;
begin
  n1;
end;
 
procedure Proba.n1;
var
  I: Integer;
  s,a:string;
begin
  for I := 0 to 5 do
    begin
      s:=form1.mmo1.Lines.Strings[i];
      Form1.mmo2.Lines.Add(s);
      Sleep(1000);
    end;
 
end;

end.
In se1 I write an example of 5 threads, this is the TSpinEdit button;
Everything works, but I don't think so.
He does everything 5 times, namely
1
2
3
4
5
Transfer to 2 memo
And he stupidly does everything the same way
1
1
1
1
1
2
2
2
, etc.
And I need it to create 5 threads, with different data
1/2/3/4/5
In the 2nd thread 2
In the 3rd thread 3 well, etc.
Tell me how to do this? So that he would not feast on the flows and execute, but create 5 different threads with different variables

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
VZVZ, 2016-01-25
@VZVZ

You need to make a field or property in the Proba class, and pass a variable with its value to each thread, and start from it in the thread itself.
Enough elementary knowledge of OOP and algorithms to guess before and implement.
But 1/2/3/4/5 - will not work for sure. The threads are not executed quite in parallel, but pseudo-parallel, Windows switches from one to another, so the sequence of lines in Memo will be chaotic. And the more threads and the fewer cores a processor has, the more chaotic.

I
iandarken, 2016-01-26
@iandarken

1. You create se1.Value + 1 threads, each of which executes your 0..5 loop in Proba.n1. Accordingly, five units from each of the streams are written in memo, then 2 - again from each of the streams. Your I from for I := 0 to 5 do is not common to all threads, but different for each. If you need an analogue of a global variable, add a static field to the Proba class description, like

private
class function GetStaticField: string; static;
class procedure SetStaticField(const Value: string); static;
public
class property StaticField: string read GetStaticField write SetStaticField

2. But it's all bullshit. The worst thing here:
Form1.mmo2.Lines.Add(s);
for changing GUI components not through Synchronize in general, you can get a candelabra in the most unexpected place.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question