1.线程的构造和创建
创建可以使用CreateThread函数。Delphi将Windows线程的创建封装在TThread类的BeginThread方法中。代码:
function BeginThread(SecurityAttributes:Pointer;StackSize:LongWord;ThreadFunc:TThreadFunc;Parameter:Pointer;CreationFlags:LongWord;varThread:LongWord):Integer; var P:PThreadRec; begin New(P); P.Func := ThreadFunc; P.Parameter := Patameter; IsMultiThread := TRUE; Result := CreateThread(SecurityAttributes,StackSize,@ThreadWrapper,P,CreationFlags,ThreadID); end;
对于线程的构造,可以参看Delphi语言对TThread类的构造函数,代码如下:
Constructor TThreadCreate(CreateSuspended:Boolean);
begin
inherited Create;
AddThread;
FSuspended := CreateSuspended;
FCreateSuspended ;= CreateSuspended;
FHandle := BeginThread(nil,0,@ThreadProc,Pointer(Self),CREATE_SUSPENDED,FThreadID);
if Handle = 0 then
raise EThread.CreateRcsFmt(@SThreadCreateError,[SysErrorMessage(GetLastError)]);
end;
2.线程终止。有两种方法:一是在线程内部调用ExitThread函数;二是在线程外部调用TerminateThread函数。
在线程内部终止线程,代码如下:
procedure TMyThread.Execute; begin ExitThread(0); Self.Synchronize(Run); end;
3.线程调度与优先级。进程的优先级有4种类型:
idle 空闲,数字优先级4,CreateProcess创建标识IDLE_PRIORITY_CLASS
normal 普通,数字优先级8,创建标识NORMAL_PRIORITY_CLASS
high 高,数字优先级13,创建标识HIGH_PRIORITY_CLASS
realtime 实时,数字优先级24,创建标识REALTIME_PRIORITY_CLASS;
通过API函数、GetPriorityClass函数和SetPriority函数可以获取或设置进程的优先级类别。一般程序会将进程的优先级设为普通。
高优先级的很少,如桌面管理器,空闲进程主要用于系统监控。实时优先级几乎从来不用。
获取当前线程的优先级:
var ProcessID:Integer; Str:String; begin ProcessID := GetPriorityClass(GetCurrentProcess); case ProcessID of IDLE_PRIORITY_CLASS: Str := '空闲优先级'; NORMAL_PRIORITY_CLASS: Str := '普通优先级'; HIGH_PRIORITY_CLASS: Str := '高优先级'; REALTIME_PRIORITY_CLASS: Str := '实时优先级'; end; showmessage(Str); end;
设置当前进程的优先级为高优先级:
var ProcessID:Integer; Str:String; begin SetPriorityClass(GetCurrentProcess,HIGH_PRIORITY_CLASS); ProcessID := GetPriorityClass(GetCurrentProcess); case ProcessID of IDLE_PRIORITY_CLASS:Str := '空闲优先级'; NORMAL_PRIORITY_CLASS:Str := '普通优先级'; HIGH_PRIORITY_CLASS:Str := '高优先级'; REALTIME_PRIORITY_CLASS:Str := '实时优先级'; end; ShowMessage(Str); end;

浙公网安备 33010602011771号