A
awfigsk
Unregistered / Unconfirmed
GUEST, unregistred user!
unit threadUnit;<br><br>interface<br><br>uses<br> Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,<br> StdCtrls, Gauges;<br><br>type<br> TForm1 = class(TForm)<br> CreateThread: TButton;<br> procedure CreateThreadClick(Sender: TObject);<br> private<br> ThreadHandle : THandle;<br> ThreadHandle1 : THandle;<br> ThreadHandle2 : THandle;<br> MutexHandle: THandle;<br> { Private declarations }<br> public<br> { Public declarations }<br> end;<br><br>var<br> Form1: TForm1;<br><br>implementation<br><br>{$R *.DFM}<br><br>function ThreadFunc0(Info: Pointer): Integer; stdcall<br>var<br> ICount: Integer; // general loop counter<br> CountStr: string; // holds a string representation of the counter<br>begin<br> WaitForSingleObject(Form1.MutexHandle, INFINITE);<br><br> for ICount := 1 to 10000 do<br> begin<br> CountStr := IntToStr(ICount);<br> Form1.Canvas.TextOut(10, 10, 'Thread 1 '+CountStr);<br> end;<br><br> ReleaseMutex(Form1.MutexHandle);<br> ExitThread(1);<br>end;<br><br>function ThreadFunc1(Info: Pointer): Integer; stdcall<br>var<br> ICount: Integer; // general loop counter<br> CountStr: string; // holds a string representation of the counter<br>begin<br> WaitForSingleObject(Form1.MutexHandle, INFINITE);<br> for ICount := 1 to 10000 do<br> begin<br> CountStr := IntToStr(ICount);<br> Form1.Canvas.TextOut(110, 10, 'Thread 2 '+CountStr);<br> end;<br><br> ReleaseMutex(Form1.MutexHandle);<br> ExitThread(2);<br>end;<br><br>function ThreadFunc2(Info: Pointer): Integer; stdcall<br>var<br> ICount: Integer; // general loop counter<br> CountStr: string; // holds a string representation of the counter<br> LocalMutexHandle: THandle; // holds a handle to the mutex<br>begin<br> LocalMutexHandle := OpenMutex(MUTEX_ALL_ACCESS, FALSE, 'MyMutex');<br><br> WaitForSingleObject(LocalMutexHandle, INFINITE);<br><br> for ICount := 1 to 10000 do<br> begin<br> CountStr := IntToStr(ICount);<br> Form1.canvas.TextOut(210, 10, 'Thread 3 '+CountStr);<br> end;<br><br> ReleaseMutex(LocalMutexHandle);<br><br> CloseHandle(LocalMutexHandle);<br> ExitThread(3);<br>end;<br><br>procedure TForm1.CreateThreadClick(Sender: TObject);<br>var<br> ThreadId0, ThreadId1, ThreadId2: DWORD; // holds thread identifiers<br>begin<br> MutexHandle := CreateMutex(nil, False,'MyMutex');<br><br> ThreadHandle := Windows.CreateThread(nil, 0, @ThreadFunc0, nil, 0, ThreadId0);<br><br> ThreadHandle1 := Windows.CreateThread(nil,0, @ThreadFunc1, nil, 0, ThreadId1);<br><br> ThreadHandle2 := Windows.CreateThread(nil,0, @ThreadFunc2, nil, 0, ThreadId2);<br><br> Sleep(1000);<br><br> WaitForSingleObject(MutexHandle, INFINITE);<br><br> CloseHandle(MutexHandle);<br>end;<br><br>上面这段代码执行后,线程3好像不会执行,但是我如果将线程3的建立语句ThreadHandle2=....放到ThreadHandle或Threadhandle1前面,则处理第三个位置的Thread建立语句好像都不会执行,并且我将Sleep的值设大也不会执行。<br>但当我在ThreadFunc2中最前面加入一个showmessage()语句来进行调试时,Thread3又可以执行,去掉这条语句就不会执行。这个问题是出在哪?<br>还请高手大侠们指点,谢谢!