Re: Changing a variable inside of TThread from outside of the Thread.



<Landiin@xxxxxxxxx> schreef in bericht
news:1161315979.554147.65340@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
I'm very new to Threading and playing around with them to try and learn
them.

I've ran into an access violation when trying to change a variable in
the thread from out side the thread.

What I doing is having a thread process some large XML files. In stead
of having the main thread looked in loops I've decided to try my hand
at threading.

Here is the basic/simplified thread code

Type
MyThread = class(TThread)
private
FCancel: Boolean;
...
protected
procedure Execute; override;
public
constructor Create(APath: String; ACallBack: TSyncCallback);
procedure Cancel;
end;

implementation

constructor MyThread.Create(APath: String; ACallBack: TSyncCallback);
begin
inherited Create(True);
...
resume;
end

procedure Execute;
begin
while SomeNode <> nil do
begin
....
if FCancel then Breake;
....
end;
end

procedure Cancel;
begin
FCancel := True;
end;

When ever I do MyThread.Cancel from the forms main thread I get an
access violation when execution reaches FCancel := True;


Guessing that you've left out the class names in your code...
I do not see what causes the AV, but maybe I can contribute with three
remarks:
1) I would not put Resume in the creator. If you want the thread to start
upon creation, use Create(false). Check help: the parameter tells whether to
start immediately or wait until resume is called.
2) Tthread has a procedure Terminate. You call it from the main thread to
signal that it should terminate. In the execute loop then replace If Fcancel
by If Terminated. Check help.
3) there is a classic article on threads by Martin Harvey. See
http://web.archive.org/web/20041112062343/www.pergolesi.demon.co.uk/prog/threads/ToC.html

Tom


.



Relevant Pages