多线程编程(9) - 认识等待函数 WaitForSingleObject
一下子跳到等待函数 WaitForSingleObject, 是因为下面的 Mutex、Semaphore、Event、WaitableTimer 等同步手段都要使用这个函数; 不过等待函数可不止 WaitForSingleObject 它一个, 但它最简单.
function WaitForSingleObject( hHandle: THandle; {要等待的对象句柄} dwMilliseconds: DWORD {等待的时间, 单位是毫秒} ): DWORD; stdcall; {返回值如下:} 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
posted on 2009-02-13 15:07 万一 阅读(26335) 评论(6) 编辑 收藏