Suddenly jump to wait function WaitForSingleObject, because the following Mutex, Semaphore, Event, Waitabletimer and other synchronization means to use this function; But the wait function does more than waitforsingleobject it, but it's the simplest.
function WaitForSingleObject(
hHandle: THandle; {要等待的对象句柄}
dwMilliseconds: DWORD {等待的时间, 单位是毫秒}
): DWORD; stdcall; {返回值如下:}
WAIT_OBJECT_0 {等着了, 本例中是: 等的那个进程终于结束了}
WAIT_TIMEOUT {等过了点(你指定的时间), 也没等着}
WAIT_ABANDONED {好不容易等着了, 但人家还是不让咱执行; 这一般是互斥对象}
//WaitForSingleObject 的第二个参数一般给常数值 INFINITE, 表示一直等下去, 死等.
WaitForSingleObject wait for what? In multithreading is waiting for the end of another thread, quickly to execute their own code; But it can wait for the object can be more than threads; Here is an example that waits for the end of another process to run the effect diagram:
Code files: 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; {Process Handle}
{When the process of waiting for a specified handle ends}
function Mythreadfun (p:pointer): DWORD; stdcall;
Begin
If WaitForSingleObject ( hprocess, INFINITE) = Wait_object_0 then
Form1.text: = Format (' process%d closed ', [hprocess]);
Result: = 0;
End;
{Start a process and establish a new thread to wait for it to end}
procedure Tform1.button1click (sender:tobject);
var
pinfo:tprocessinformation ;
Sinfo:tstartupinfo;
Path:array[0..max_path-1] of Char;
Threadid:dword;
Begin
{Get the path to Notepad}
GetSystemDirectory (path, MAX_PATH);
StrCat (Path, ' \notepad.exe ');
{Open Notepad with CreateProcess and get its process handle, then establish thread monitoring}
Fillchar (Sinfo, SizeOf (sinfo), 0);
If CreateProcess (Path, nil, nil, nil, False, 0, Nil, nil, sinfo, pinfo) then
begin
Hprocess: = Pinfo.hpro Cess {Get process Handle}
Text: = Format (' Process%d started ', [hprocess]);
CreateThread (nil, 0, @MyThreadFun, nil, 0, ThreadID); {Establish thread monitoring}
End;
End;
End.
Form file: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