转载自:万一的博客
一下子跳到等待函数 WaitForSingleObject,是因为下面的Mutex、Semaphore、Event、WaitableTimer等同步手段都要使用这个函数。不过等待函数可不止WaitForSingleObject这一个,但是它是最简单的
function WaitForSingleObject( hHandle: THandle; //要等待的对象句柄 dwMillseconds: DWORD; //等待的时间,单位是毫秒 ): DWORD; srdcall;
返回值说明如下
WAIT_OBJECT_0 {等着了,本例中是:等的那个进程终于结束了} WAIT_TIMEOUT {等过了点(你指定的时间),也没等着} WAIT_ABANDONED {好不容易等着了,但是人家还是不让咱执行;这一般是互斥对象}
//WaitForSingleObject 的第二个参数一般给常数值 INFINITE, 表示一直等下去, 死等.
WaitForSingleObject等待什么?在多线程就是等待另一个线程的结束,快来执行自己的代码;不过他可以等待的对象可不止线程;这里先来一个等待另一个进程结束的例子,运行效果图
代码如下
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1=class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} var hProcess: Thandle; {进程句柄} {等待一个指定句柄的进程什么时候结束} function MyThreadFun(p: Pointer);DWORD;stdcall; begin if WaitForSingleObject(hProcess, INFINITE)=WAIT_OBJECT_0 then Form1.Text:= Format(‘进程 %d 已关闭‘,[hProcess]); Result:= 0; end; procedure TForm1.Button1Click(Sender: Tobject); var pInfo: TProcessInformation; sInfo: TStartupInfo; Path: Array[0..MAX_PATH-1] of Char; ThreadID: DWORD; begin {先获得记事本的路径} GetSystemDirectory(Path, MAX_PATH); StrCat(Path, ‘\notepad.exe‘); {用 CreateProcess 打开记事本并获取进程句柄,然后建立线程监视} FillChar(sInfo, SizeOf(sInfo),0); if CreateProcess(Path, nil, nil, nil, False, 0, nil, nil, sInfo, pInfo) then begin hProcess:= pInfo.hProcess; //获取进程句柄 Text:= Format(‘进程 %d 已启动‘, [hProcess]); CreateThread(nil, 0, @MyThreadFun, nil, 0, ThreadID); //建立线程监视 end; end; end.
窗体文件
object Form1: TForm1 Left = 0 Top = 0 Caption = ‘Form1‘ ClientHeight = 124 ClientWidth = 241 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = ‘Tahoma‘ Font.Style = [] OldCreateOrder = False PixelsPerInch = 96 TextHeight = 13 object Button1: TButton Left = 88 Top = 56 Width = 75 Height = 25 Caption = ‘Button1‘ TabOrder = 0 OnClick = Button1Click end end
时间: 2024-12-29 23:30:49