var
Form1: TForm1;
Xs: TCriticalSection; //uses SyncObjsimplementation
{$R *.dfm}
function TmyThreadFun(p: Pointer): DWORD; stdcall;
var
i: Integer;
begin
Xs.Enter;
for i := 0 to 100 do Form1.mmo1.Lines.Add(IntToStr(i));
Xs.Leave;
Result := 0;
end;
procedure TForm1.Button1Click(Sender: TObject);
var id: Cardinal;
begin
xs := TCriticalSection.Create;
mmo1.Clear;
CreateThread(nil, 0, @TmyThreadfun, nil, 0, id);
CreateThread(nil, 0, @TmyThreadfun, nil, 0, id);
CreateThread(nil, 0, @TmyThreadfun, nil, 0, id);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin xs.Free;
end;
{var
CS: TRTLCriticalSection;
{声明一个 TRTLCriticalSection 结构类型变量;
它应该是全局的} InitializeCriticalSection(CS);
{初始化} EnterCriticalSection(CS);
{开始: 轮到我了其他线程走开}
LeaveCriticalSection(CS); {结束: 其他线程可以来了}
DeleteCriticalSection(CS); {删除: 注意不能过早删除} //也可用 TryEnterCriticalSection 替代 EnterCriticalSection.}
implementation
{$R *.dfm}
var CS: TRTLCriticalSection;
function MyThreadFun(p: Pointer): DWORD; stdcall;
var i: Integer;
begin
EnterCriticalSection(CS);
for i := 0 to 99 do Form1.mmo1.line.Add(IntToStr(i));
LeaveCriticalSection(CS);
Result := 0;
end;
procedure TForm1.Button1Click(Sender: TObject);
var ID: DWORD;
begin
CreateThread(nil, 0, @MyThreadFun, nil, 0, ID); CreateThread(nil, 0, @MyThreadFun, nil, 0, ID); CreateThread(nil, 0, @MyThreadFun, nil, 0, ID);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
InitializeCriticalSection(CS);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
DeleteCriticalSection(CS);
end;
end.