Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Thread - use of variables 1

Status
Not open for further replies.

gp4

Technical User
Sep 27, 2002
30
AU
I am using Delphi 7 and would like to know if it is possible to read variables that exist in the Thread that is instantiated, from the main code. If so, how should I declare these variables in the threaded code.

N.B my main code is in unit1.pas, and the thread code in unit2.pas for example.
Thanks.
 
Hi.
Override the TThread.Create constructor to pass the mainform as an argument.
The MainForm private variable in the thread is called FMainForm in this example;

Code:
constructor TThread.Create(CreateSuspended: Boolean; var MainForm: TForm); override;
begin
  FMainForm := MainForm;
  Inherited Create(CreateSuspended);
end;

//Nordlund
 
Hi Nordlund,
Thanks for your feedback.
I guess this allows you to access variables that exist in the mainform, from the new thread.
How would you access the variables in the thread from the main application though?
Thanks
 
That's little bit harder to explain.
Somehow you have to keep track of the running threads, maybe in a TList. Then you can create public members in the threads, end then control them by using
TMyThread(List[x]).TheVariable

Explain a little bit more how you're going to use the threads, and why you have to store in them.

//Nordlund
 
Hi Nordlund,
I'm using the thread to do a very large filecopy/cut operation (a few GB) using filestreams.
I wanted to get access to the filestream.pos property in the thread from the main application to determine its progress.

Thanks
 
Hi.
If you only using one thread, you can access the Filestream by the variable you haved defined for this thread. (MyThread.FileStream.Pos)

Otherwise, if you are 100% sure you will not use another "filecopy" thread you can use a global variable...
But this is not "Threadsafe" due to use of global variables.

I would prefer the first way... Declare a variable for the thread, and make the FileStream public in the thread, then you can access it "propertly"...

//Nordlund
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top