谁能讲讲线程同步?(200分)

  • 主题发起人 主题发起人 老狼78
  • 开始时间 开始时间

老狼78

Unregistered / Unconfirmed
GUEST, unregistred user!
我的程序总出问题,到底应该怎么同步?
 
给你个例子,自己看吧
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.
 
接受答案了.
 
后退
顶部