关于互斥对象 线程同步的问题
学习多线程的时候看到了这样一段代码!///////////////////////////////////////////////////////////////////////////////////////
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
MutexHandle: THandle;
ThreadHandle, ThreadHandle1, ThreadHandle2: THandle;
implementation
{$R *.DFM}
function ThreadFunc1(Info: Pointer): Integer; stdcall;
var
ICount: Integer;
CountStr: string;
begin
WaitForSingleObject(MutexHandle, INFINITE);
for ICount := 1 to 100000 do
begin
CountStr := IntToStr(ICount);
Form1.Canvas.TextOut(10, 10, 'Thread 1 ' + CountStr);
end;
ReleaseMutex(MutexHandle);
ExitThread(1);
end;
function ThreadFunc2(Info: Pointer): Integer; stdcall;
var
ICount: Integer;
CountStr: string;
begin
WaitForSingleObject(MutexHandle, INFINITE);
for ICount := 1 to 100000 do
begin
CountStr := IntToStr(ICount);
Form1.Canvas.TextOut(160, 10, 'Thread 2 ' + CountStr);
end;
ReleaseMutex(MutexHandle);
ExitThread(2);
end;
function ThreadFunc3(Info: Pointer): Integer; stdcall;
var
ICount: Integer;
CountStr: string;
LocalMutexHandle: THandle;
begin
LocalMutexHandle := OpenMutex(MUTEX_ALL_ACCESS, FALSE, 'MyMutex');
WaitForSingleObject(LocalMutexHandle, INFINITE);
for ICount := 1 to 100000 do
begin
CountStr := IntToStr(ICount);
Form1.canvas.TextOut(310, 10, 'Thread 3 ' + CountStr);
end;
ReleaseMutex(LocalMutexHandle);
CloseHandle(LocalMutexHandle);
ExitThread(3);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
ThreadId1, ThreadId2, ThreadId3: DWORD;
begin
if MutexHandle<>DWORD(-1) then
CloseHandle(MutexHandle);
MutexHandle := CreateMutex(nil, False, 'MyMutex');
ThreadHandle := CreateThread(nil, 0, @ThreadFunc1, nil, 0, ThreadId1);
ThreadHandle1 := CreateThread(nil, 0, @ThreadFunc2, nil, 0, ThreadId2);
ThreadHandle2 := CreateThread(nil, 0, @ThreadFunc3, nil, 0, ThreadId3);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
MutexHandle:=DWORD(-1);
end;
end.
///////////////////////////////////////////////////////////////////////////////////////////
就编译运行了下!令我白死不的其解!运行结果很有随即性! 我多次运行有以下几种情况:
1.点击运行按钮 但是并没有反映;
2.点击后直接程序错误;
3.运行 线程1 线程2 线程3(都运行完就是都显示到100000)(我认为应该的情况);
4.只线程1(并没有显示到100000);
5.运行完线程1后 直接显示错误;
后面还有几种 真是饶人啊!
有哪个高手可以帮我解释下! 将下那个互斥对象的工作原理 希望详细点啊!