MutexFrm.pas
上传用户:psxgmh
上传日期:2013-04-08
资源大小:15112k
文件大小:2k
- unit MutexFrm;
- interface
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs, StdCtrls;
- type
- //定义一个线程类
- TsyncThread = class(TThread)
- protected
- procedure execute; override;
- end;
- TfrmMutex = 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
- frmMutex: TfrmMutex;
- //数据全局区
- GlobalData: array[1..MaxSize] of integer;
- IncNum: Integer = 0;
- //定义互斥对象句柄
- HMutex: THandle = 0;
- implementation
- {$R *.dfm}
- //线程执行主体
- procedure TSyncThread.execute;
- var
- i: integer;
- WaitReturn: DWORD;
- begin
- FreeOnTerminate := True;
- //进入同步,防止其他线程访问
- WaitReturn := WaitForSingleObject(HMutex, INFINITE);
- if WaitReturn = Wait_Object_0 then
- for i := 1 to Maxsize do
- begin
- Inc(IncNum);
- GlobalData[i] := IncNum;
- Sleep(10);
- end;
- end;
- //在窗体创建时,创建互斥量
- procedure TfrmMutex.FormCreate(Sender: TObject);
- begin
- HMutex := CreateMutex(nil, false, nil);
- end;
- //在窗体释放时,释放互斥量
- procedure TfrmMutex.FormDestroy(Sender: TObject);
- begin
- CloseHandle(HMutex);
- end;
- //创建线程实例
- procedure TfrmMutex.btnExecuteClick(Sender: TObject);
- begin
- Thread1 := TSyncThread.Create(false);
- Thread1.OnTerminate := Thread1Done;
- Thread2 := TSyncThread.Create(false);
- Thread2.OnTerminate := Thread2Done;
- end;
- //当线程1执行完后,将GlobalData数据显示出来
- procedure TfrmMutex.Thread1Done(sender: TObject);
- var
- i: integer;
- begin
- ListBox1.Items.Clear;
- for i := 1 to MaxSize do
- Listbox1.Items.Add(intToStr(GlobalData[i]));
- //解除互斥,让其他线程可以访问
- ReleaseMutex(HMutex);
- end;
- //当线程2执行完后,将GlobalData数据显示出来
- procedure TfrmMutex.Thread2Done(sender: TObject);
- var
- i: integer;
- begin
- ListBox2.Items.Clear;
- for i := 1 to MaxSize do
- Listbox2.Items.Add(intToStr(GlobalData[i]));
- //解除互斥,让其他线程可以访问
- ReleaseMutex(HMutex);
- end;
- end.