贴一篇 互斥的源程序<br>unit MutexFrm;<br>interface<br>uses<br> Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,<br> Dialogs, StdCtrls;<br>type<br> //定义一个线程类<br> TsyncThread = class(TThread)<br> protected<br> procedure execute; override;<br> end;<br> TfrmMutex = class(TForm)<br> ListBox1: TListBox;<br> btnExecute: TButton;<br> ListBox2: TListBox;<br> Label1: TLabel;<br> Label2: TLabel;<br> procedure btnExecuteClick(Sender: TObject);<br> procedure FormCreate(Sender: TObject);<br> procedure FormDestroy(Sender: TObject);<br> private<br> //定义线程实例变量<br> Thread1, Thread2: TSyncThread;<br> //自定义过程,在线程结束时调用<br> procedure Thread1Done(sender: TObject);<br> procedure Thread2Done(sender: TObject);<br> { Private declarations }<br> public<br> { Public declarations }<br> end;<br>const<br> MaxSize = 100;<br>var<br> frmMutex: TfrmMutex;<br> //数据全局区<br> GlobalData: array[1..MaxSize] of integer;<br> IncNum: Integer = 0;<br> //定义互斥对象句柄<br> HMutex: THandle = 0;<br>implementation<br>{$R *.dfm}<br>//线程执行主体<br>procedure TSyncThread.execute;<br>var<br> i: integer;<br> WaitReturn: DWORD;<br>begin<br> FreeOnTerminate := True;<br> //进入同步,防止其他线程访问<br> WaitReturn := WaitForSingleObject(HMutex, INFINITE);<br> if WaitReturn = Wait_Object_0 then<br> for i := 1 to Maxsize do<br> begin<br> Inc(IncNum);<br> GlobalData := IncNum;<br> Sleep(10);<br> end;<br>end;<br>//在窗体创建时,创建互斥量<br>procedure TfrmMutex.FormCreate(Sender: TObject);<br>begin<br> HMutex := CreateMutex(nil, false, nil);<br>end;<br>//在窗体释放时,释放互斥量<br>procedure TfrmMutex.FormDestroy(Sender: TObject);<br>begin<br> CloseHandle(HMutex);<br>end;<br>//创建线程实例<br>procedure TfrmMutex.btnExecuteClick(Sender: TObject);<br>begin<br> Thread1 := TSyncThread.Create(false);<br> Thread1.OnTerminate := Thread1Done;<br> Thread2 := TSyncThread.Create(false);<br> Thread2.OnTerminate := Thread2Done;<br>end;<br>//当线程1执行完后,将GlobalData数据显示出来<br>procedure TfrmMutex.Thread1Done(sender: TObject);<br>var<br> i: integer;<br>begin<br> ListBox1.Items.Clear;<br> for i := 1 to MaxSize do<br> Listbox1.Items.Add(intToStr(GlobalData));<br> //解除互斥,让其他线程可以访问<br> ReleaseMutex(HMutex);<br>end;<br>//当线程2执行完后,将GlobalData数据显示出来<br>procedure TfrmMutex.Thread2Done(sender: TObject);<br>var<br> i: integer;<br>begin<br> ListBox2.Items.Clear;<br> for i := 1 to MaxSize do<br> Listbox2.Items.Add(intToStr(GlobalData));<br> //解除互斥,让其他线程可以访问<br> ReleaseMutex(HMutex);<br>end;<br>end.