使用CreateThread时怎样传递参数(100分)

  • 主题发起人 主题发起人 happyxhl
  • 开始时间 开始时间
H

happyxhl

Unregistered / Unconfirmed
GUEST, unregistred user!
function Exec(abc:Integer):Integer;
begin
Result := abc*abc/3;
end;

procedure ThreadExec;
var
threadhandle:THandle;
threadid:dword;
begin
threadhandle := CreateThread(nil,0,@Exec,nil,0,threadid);
end;
//请问abc的值如何传,且如何得到函数返回值啊?望高手帮忙看看
//上面代码只是自己感觉应该这样用,肯定不对,请指正。
 
当然不对,不过你干嘛不用TThread对象呢?这样很简单啊。传任何值只需修改Create构造函数再加几个私有变量即可啊。给你一个例子:
unit uTerminateProcessThread;
interface
uses
Classes, Tlhelp32;
type
TTerminateProcessThread = class(TThread)
private
{ Private declarations }
FProcessEntry: TProcessEntry32;
FImmediatelyTerminate: Boolean;
FAfterSeconds: Cardinal;
protected
procedure Execute;
override;
public
constructor Create(const ProcessEntry: TProcessEntry32;
const ImmediatelyTerminate: Boolean;
const AfterSeconds: Cardinal);
end;

implementation
uses CommonProc, SysUtils;
{ TTerminateProcessThread }
constructor TTerminateProcessThread.Create(const ProcessEntry: TProcessEntry32;
const ImmediatelyTerminate: Boolean;
const AfterSeconds: Cardinal);
begin
inherited Create(True);
FProcessEntry := ProcessEntry;
FImmediatelyTerminate := ImmediatelyTerminate;
FAfterSeconds := AfterSeconds;
FreeOnTerminate := True;
Resume;
end;

procedure TTerminateProcessThread.Execute;
begin
{ Place thread code here }
if not FImmediatelyTerminate then
Sleep(FAfterSeconds * 1000);
TerminateProcessEx(FProcessEntry.th32ProcessID);//这个是我的自定义函数,关闭一个指定进程
end;

end.
 
忘了说了,调用的时候直接:
begin
TTerminateProcessThread.Create(AProcessEntry32, False, 5);
end
5秒后自动关闭AProcessEntry32参数指定的进程。
 
Exec(abc: TPoint);
stdcall;
begin

P^{Do you want}
end;

P: ^Integer;
P := 1;
threadhandle:=createthread(nil,0,@co,P,0,threadID);//
 
function Exec(abc:Integer);//这个不能是函数,应该过程,
var
param:integer;
begin
threadhandle := CreateThread(nil,0,@Exec,@param,0,threadid);
^-------参数在此传递
end;
 
zqw0117:
用过TThread类,还是觉得API来的方便,至少代码要少很多。
qince:
传参这么麻烦吗?如果我有多个参数要传,当如何是好,难道要把参数定义成记录型。
 
你说对了,如果你要传递多个参数就要做成记录类型
 
谢了,我去试试。再问一下,用全局变量行不行,Exec函数不写参数,过程中直接调用全局变量?
 
你试试看,不一定有调试成功,但大致是这么回事。
----------
---------
type
pdata=^Tdata
Tdata=record
x:integer;
y:integer;
end;

----------
---------
implementation
--------
-------
procedure ThreadExec;
var
threadhandle:THandle;
threadid:dword;
data:pdata;
begin
new(data);
data^.x:=10;
data^.y:=20;
threadhandle := CreateThread(nil,0,@Exec,data,0,threadid);
end;

 

Similar threads

S
回复
0
查看
1K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
900
SUNSTONE的Delphi笔记
S
后退
顶部