使用阻塞技术或或者互斥.
//使用阻塞的示例
unit Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TMainForm = class(TForm)
Button1: TButton;
ListBox1: TListBox;
procedure Button1Click(Sender: TObject);
private
procedure ThreadsDone(Sender: TObject);
end;
TFooThread = class(TThread)
protected
procedure Execute;
override;
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
const
MaxSize = 128;
var
NextNumber: Integer = 0;
do
neFlags: Integer = 0;
GlobalArray: array[1..MaxSize] of Integer;
CS: TRTLCriticalSection;
function GetNextNumber: Integer;
begin
Result := NextNumber;
// return global var
inc(NextNumber);
// inc global var
end;
procedure TFooThread.Execute;
var
i: Integer;
begin
OnTerminate := MainForm.ThreadsDone;
EnterCriticalSection(CS);
// CS begin
s here
for i := 1 to MaxSizedo
begin
GlobalArray := GetNextNumber;
// set array element
Sleep(5);
// let thread intertwine
end;
LeaveCriticalSection(CS);
// CS ends here
end;
procedure TMainForm.ThreadsDone(Sender: TObject);
var
i: Integer;
begin
inc(DoneFlags);
ifdo
neFlags = 2 then
begin
// make sure both threads finished
for i := 1 to MaxSizedo
{ fill listbox with array contents }
Listbox1.Items.Add(IntToStr(GlobalArray));
DeleteCriticalSection(CS);
end;
end;
procedure TMainForm.Button1Click(Sender: TObject);
begin
InitializeCriticalSection(CS);
TFooThread.Create(False);
// create threads
TFooThread.Create(False);
end;
end.