怎麽在一个线程中调用主程序中私有的过程和函数(50分)

C

cmdline

Unregistered / Unconfirmed
GUEST, unregistred user!
我写了一个程序,是给数组赋值并在listbox里显示出来,是用的临界区的方法
在线程unit2中,我也添加了uses unit1为什麽却不能在线程中调用unit1中的过程
具体程序在下面:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
ListBox1: TListBox;
procedure Button1Click(Sender: TObject);
private
procedure ThreadsDone(sender:TObject);
public
end;

const MaxSize=128;
var
Form1: TForm1;
NextNumber:Integer=0;
do
neFlags:Integer=0;
GlobalArray:array[1..MaxSize] of Integer;
CS:TRTLCriticalSection;
function GetnextNumber:Integer;
implementation
{$R *.dfm}
uses unit2;//调用线程
function GetnextNumber:Integer;
begin
Result:=NextNumber;
Inc(NextNumber);
end;

procedure TForm1.ThreadsDone(Sender:TObject);
var
i:Integer;
begin
Inc(DoneFlags);
ifdo
neFlags=2 then
begin
for i:=1 to MaxSizedo
listBox1.Items.Add(IntToStr(GlobalArray));
DeleteCriticalSection(CS);
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
InitializeCriticalSection(CS);
TFooThread.Create(false);
TFooThread.Create(false);
end;

end.
--------------------------------------------------------------------------------
unit Unit2;//线程部分
interface
uses
Unit1,Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;//调用unit1;
type
TFooThread = class(TThread)
private
{ Private declarations }
protected
procedure Execute;
override;
end;

implementation
{ Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TFooThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
}
{ TFooThread }
procedure TFooThread.Execute;
var
i:Integer;
begin
OnTerminate:=Form1.ThreadsDone;//编译到这句时报错(我在unit1中已经声明过了)
EnterCriticalSection(CS);
for i:=1 to MaxSizedo
begin
GlobalArray:=GetNextNumber;
Sleep(5);
end;
LeaveCriticalSection(CS);
end;

end.
-------------------------------------------------------------------------------
上面程序报错为:Undeclared identifier:’ThreadDone’
 
放在public里面
 
两种方法:
1:把ThreadDone放在public里
2:把线程部分放到窗体所在单元里
 
to gulang,
两种方法:
1:把ThreadDone放在public里
2:把线程部分放到窗体所在单元里
这两种方法我都试过
还是一样的
 
声明procedure ThreadsDone(sender:TObject);带参数了
后面调用
OnTerminate:=Form1.ThreadsDone;
怎么没参数?
 
子线程调用主线程比较好的办法是发消息 而不是直接引用函数
应该在子线程创建时将主窗体的handel传给这个线程
线程执行到需要调用窗体函数的地方调用windows的postmessage或者sendmessage由窗体自己执行这个函数
ps:线程直接引用主窗体的第一个问题就是vcl是非线程安全的 你的线程如果没有同步则很容易出现异常的崩溃
 
多人接受答案了。
 
顶部