unit Unit1;
{利用临界区同步多线程}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
type
TMainForm = class(TForm)
Button1: TButton;
Button2: TButton;
ListBox1: TListBox;
StatusBar1: TStatusBar;
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure ThreadsDone(Sender: TObject);
public
{ Public declarations }
end;
TIniThread=class(TThread) // 数组初始化线程
protected
procedure Execute;Override;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
const
MaxSize=128;
var
NextNum: Integer=0;
do
neFlags: Integer=0;
GlobalArray: array[1..MaxSize] of Integer;
// 待初始化的数组
CS: TRTlCriticalSection;
// 创建临界区变量
function GetNextNum:Integer;
// 获取下一个数
begin
Result:=NextNum;
Inc(NextNum);
end;
procedure TIniThread.Execute;
// 线程的执行函数
var
i: Integer;
begin
// StatusBar1.SimpleText:='线程执行函数';
OnTerminate:= MainForm.ThreadsDone;
// 进入临界区
// 在第一个线程调用了 EnterCriticalSection(CS);后, 所有别的线程不能再进入该代码块
// 下一个线程要等第一个线程调用LeaveCriticalSection(CS);
后才能被唤醒.
EnterCriticalSection(CS);
for i:=1 to MaxSizedo
begin
GlobalArray
:= GetNextNum;
// 数组赋值
Sleep(5);
// 线程挂起
end;
// 离开临界区
LeaveCriticalSection(CS);
end;
procedure TMainForm.Button2Click(Sender: TObject);
begin
DeleteCriticalSection(CS);
// 删除临界区
StatusBar1.SimpleText:='删除临界区';
close;
end;
procedure TMainForm.Button1Click(Sender: TObject);
begin
StatusBar1.SimpleText:='开始';
InitializeCriticalSection(CS);
// 临界区初始化
// 创建2个线程
TIniThread.Create(false);
TIniThread.Create(false);
end;
procedure TMainForm.ThreadsDone(Sender: TObject);
// 线程结束后的处理
var
i:Integer;
begin
StatusBar1.SimpleText:='线程结束后,将数组加入ListBox组件';
Inc(DoneFlags);
ifdo
neFlags=2 then
// 判断2个线程是否已经都结束
for i:=1 to MaxSizedo
ListBox1.Items.add(IntToStr(GlobalArray));
// 将数组加入ListBox组件
end;
end.