function CreateThread(
lpThreadAttributes: Pointer;
dwStackSize: DWord;
lpStartAddress: TFNThreadStartRoutine;
lpParameter: Pointer;
dwCreationFlags: DWord; {啟動選項}
var lpThreadId: DWord
): THandle; stdcall;
CreateThread 的倒數第二個參數 dwCreationFlags(啟動選項) 有兩個可選值:
0: 線程建立後立即執行入口函數;
CREATE_SUSPENDED: 線程建立後會掛起等待.
可用 ResumeThread 函數是恢復線程的運行; 可用 SuspendThread 再次掛起線程.
這兩個函數的參數都是線程句柄, 返回值是執行前的掛起計數.
什麼是掛起計數?
SuspendThread 會給這個數 +1; ResumeThread 會給這個數 -1; 但這個數最小是 0.
當這個數 = 0 時, 線程會運行; > 0 時會掛起.
如果被 SuspendThread 多次, 同樣需要 ResumeThread 多次才能恢復線程的運行.
在下面的例子中, 有新線程不斷給一個全局變量賦隨機值;
同時窗體上的 Timer 控件每隔 1/10 秒就把這個變量寫在窗體標題;
在這個過程中演示了 ResumeThread、SuspendThread 兩個函數.
運行效果圖:
代碼文件:unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Timer1: TTimer;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
hThread: THandle; {線程句柄}
num: Integer; {全局變量, 用於記錄隨機數}
{線程入口函數}
function MyThreadFun(p: Pointer): Integer; stdcall;
begin
while True do {假如線程不掛起, 這個循環將一直循環下去}
begin
num := Random(100);
end;
Result := 0;
end;
{建立並掛起線程}
procedure TForm1.Button1Click(Sender: TObject);
var
ID: DWord;
begin
hThread := CreateThread(nil, 0, @MyThreadFun, nil, CREATE_SUSPENDED, ID);
Button1.Enabled := False;
end;
{喚醒並繼續線程}
procedure TForm1.Button2Click(Sender: TObject);
begin
ResumeThread(hThread);
end;
{掛起線程}
procedure TForm1.Button3Click(Sender: TObject);
begin
SuspendThread(hThread);
end;
{下面是窗體代碼}
procedure TForm1.FormCreate(Sender: TObject);
begin
Timer1.Interval := 100;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Text := IntToStr(num);
end;
end.
窗體文件:object Form1: TForm1
Left = 0
Top = 0
Caption = 'Form1'
ClIEntHeight = 86
ClIEntWidth = 269
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object Button1: TButton
Left = 16
Top = 24
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 0
OnClick = Button1Click
end
object Button2: TButton
Left = 97
Top = 24
Width = 75
Height = 25
Caption = 'Button2'
TabOrder = 1
OnClick = Button2Click
end
object Button3: TButton
Left = 178
Top = 24
Width = 75
Height = 25
Caption = 'Button3'
TabOrder = 2
OnClick = Button3Click
end
object Timer1: TTimer
OnTimer = Timer1Timer
end
end
ResumeThread 和 SuspendThread 分別對應 TThread 的 Resume 和 Suspend 方法, 很好理解.
接下來應該是 CreateThread 的第四個參數了.