02.09.2013, 14:20
|
|
Let Me Show You
|
|
Регистрация: 30.04.2010
Адрес: Северодвинск
Сообщения: 5,426
Версия Delphi: 7, XE5
Репутация: 59586
|
|
Код:
unit Unit1;
interface
uses
SyncObjs,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TMyThread = class(TThread)
ThreadIndex: Integer;
Log: String;
constructor Create(AThreadIndex: Integer);
procedure Execute; override;
procedure UpdateLog;
end;
TForm1 = class(TForm)
Memo1: TMemo;
Memo2: TMemo;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
CriticalSection: TCriticalSection;
CurrentIndex: Integer;
function GetMemo(var S: String): Boolean;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
Randomize;
CriticalSection:=TCriticalSection.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
CriticalSection.Free;
end;
function TForm1.GetMemo(var S: String): Boolean;
begin
CriticalSection.Enter;
try
Result:=CurrentIndex<Memo1.Lines.Count;
if Result then
begin
S:=Memo1.Lines[CurrentIndex];
CurrentIndex:=CurrentIndex+1;
end;
finally
CriticalSection.Leave;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
const
N = 4;
var
i: Integer;
begin
Memo2.Clear;
CurrentIndex:=0;
for i:=1 to N do TMyThread.Create(i);
end;
{ TMyThread }
constructor TMyThread.Create(AThreadIndex: Integer);
begin
ThreadIndex:=AThreadIndex;
inherited Create(True);
FreeOnTerminate:=True;
Resume;
end;
procedure TMyThread.Execute;
var
s: String;
begin
while Form1.GetMemo(s) do
begin
Sleep(Random(50));
Log:=s;
Synchronize(UpdateLog);
end;
end;
procedure TMyThread.UpdateLog;
begin
Form1.Memo2.Lines.Add('Thread '+IntToStr(ThreadIndex)+' : '+#9+Log);
end;
end.
http://zalil.ru/34706268
__________________
Пишу программы за еду.
__________________
|