CriticalSectionfrm.pas
上传用户:psxgmh
上传日期:2013-04-08
资源大小:15112k
文件大小:2k
源码类别:
Delphi/CppBuilder
开发平台:
Delphi
- unit CriticalSectionfrm;
- interface
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs, StdCtrls;
- type
- //定义一个线程类
- TsyncThread = class(TThread)
- protected
- procedure execute; override;
- end;
- TfrmCriticalSection = class(TForm)
- ListBox1: TListBox;
- btnExecute: TButton;
- ListBox2: TListBox;
- Label1: TLabel;
- Label2: TLabel;
- procedure btnExecuteClick(Sender: TObject);
- procedure FormCreate(Sender: TObject);
- procedure FormDestroy(Sender: TObject);
- private
- //定义线程实例变量
- Thread1, Thread2: TSyncThread;
- //自定义过程,在线程结束时调用
- procedure Thread1Done(sender: TObject);
- procedure Thread2Done(sender: TObject);
- { Private declarations }
- public
- { Public declarations }
- end;
- const
- MaxSize = 100;
- var
- frmCriticalSection: TfrmCriticalSection;
- //数据全局区
- GlobalData: array[1..MaxSize] of integer;
- IncNum: Integer = 0;
- //定义TRTLCriticalSection类型变量,用于临界区
- CS: TRTLCriticalSection;
- implementation
- {$R *.dfm}
- //线程执行主体
- procedure TSyncThread.execute;
- var
- i: integer;
- begin
- FreeOnTerminate := True;
- //进入临界区
- EnterCriticalSection(CS);
- for i := 1 to Maxsize do
- begin
- Inc(IncNum);
- GlobalData[i] := IncNum;
- Sleep(10);
- end;
- end;
- //当窗体创建时,初始化临界区
- procedure TfrmCriticalSection.FormCreate(Sender: TObject);
- begin
- InitializeCriticalSection(CS);
- end;
- //当窗体释放时,释放临界区
- procedure TfrmCriticalSection.FormDestroy(Sender: TObject);
- begin
- DeleteCriticalSection(CS);
- end;
- //创建线程实例
- procedure TfrmCriticalSection.btnExecuteClick(Sender: TObject);
- begin
- Thread1 := TSyncThread.Create(false);
- Thread1.OnTerminate := Thread1Done;
- Thread2 := TSyncThread.Create(false);
- Thread2.OnTerminate := Thread2Done;
- end;
- //当线程1执行完后,将GlobalData数据显示出来
- procedure TfrmCriticalSection.Thread1Done(sender: TObject);
- var
- i: integer;
- begin
- ListBox1.Items.Clear;
- for i := 1 to MaxSize do
- Listbox1.Items.Add(intToStr(GlobalData[i]));
- //离开临界区
- LeaveCriticalSection(CS);
- end;
- //当线程2执行完后,将GlobalData数据显示出来
- procedure TfrmCriticalSection.Thread2Done(sender: TObject);
- var
- i: integer;
- begin
- ListBox2.Items.Clear;
- for i := 1 to MaxSize do
- Listbox2.Items.Add(intToStr(GlobalData[i]));
- //离开临界区
- LeaveCriticalSection(CS);
- end;
- end.