在线程中调用DLL函数问题???
由于DLL中有一个函数,运行时比较占资源,为了让界面可以作其它操作,把该函数放在线程中运行。
从Tthread派生一个类,Ttest=class(Tthread);在Ttest的Execute方法中调用DLL函数,
procedure Ttest.Execute;
begin
Freeonterminate:=true;
start();//dll函数
end;
dll函数的声明都在一个FORM单元里,动态加载,在test单元中USES了FORM单元,使其可调用DLL函数
在一个按键事件中动态加载函数如下:
TYPE sim_s=fuction ():integer:cdecl;
var start:sim_s;
procedure TForm.RzButton1Click(Sender: TObject);
var th:ttest;
h:thandle;
begin
h:=loadlibrary('test.dll');
if h<>0 then
begin
@start:=getprocaddress(h,'SimStart');
if @start<> nil then th:=ttest.Create(false);//启动线程
end;
end;
这样编译通过,运行时FORM还是不能动,线程好像没有启动一样。。不知是什么原因。
对于线程这方面也不懂只是在网上看了一些文章,也不是很理解,不知这样用是否正确,如不正确,该怎样启动一个线程来执行
DLL中的函数呢,比较着急,大家帮忙想想办法吧。。。。。
分不多请见谅。。
[解决办法]
tthread.termiante并没有真正释放线程~
安全释放线程需要用事件的形式,即在主线程退出时,对预先生成的Event进行SetEvent,然后在工作线程循环时进行判断,如果信号为signaled,则terminate,最终目的是让线程执行完毕后释放,否则会出一些堆栈的错误!
[解决办法]
//大概是这样,手头没环境
Var
QuitEvent:TEvent;
procedure Ttest.Create;
begin
Freeonterminate:=False;
Inherited;
end;
procedure Ttest.Execute;
begin
While not Terminated do
begin
if QuitEvent.WaitFor(等待时间)=signaled then Terminat;
start();//dll函数
end;
end;
initialization
QuitEvent.Create(.....);
Finalization
QuitEvent.Free;
------------------------------
在主线程退出前给它发一个信号
procedure NotifyThreadToQuit;
begin
QuitEvent.SetEvent;
end;