[Lazarus] Threads

Sven Barth pascaldragon at googlemail.com
Thu Mar 22 16:24:05 CET 2012

Am 22.03.2012 15:32, schrieb Antonio Fortuny:
> Hi folks.
> Wen launching a thread, the process responsible for the thread object
> creation and the call to TThread.Start and the thread EXECUTE procedure,
> run in parallel. That's why the SYNCHRONIZE procedure exists and that
> the developer has to pay attention to not share code between threads.
> So far, so good.
> Now imagine that the EXECUTE procedure of a thread creates a useful
> object (TMyObject) with properties and methods. This thread is launched
> half a dozen times to process half a dozen simultaneous operations.
> My question is:
> How the properties and methods of the TMyObject created in every
> launched thread are they managed from one thread to another. As far as
> the data segment is concerned, no problem, I guess that every instance
> of the TMyObject has its own data in its thread address space: no mix.
> But what about the code and the local methods stack: will it be shared ?
> And if answer is yes, to what should I take care ?
> The question is far from trivial: I try to keep the EXECUTE procedure as
> small as possible and spread the code and data over a number of
> specialized units avoiding to load the EXECUTE procedure stack with
> heavy data ans structures.
> I apologize if my question doesn't sound very clear, but it's not even
> clear in my mind :-[

I don't know whether I understood your question correctly, but I'll try 
to answer:
* Each thread has it's own stack space, so objects/data located on the 
stack is (normally) not shared between threads (an exception for example 
are writeable local consts, because they act like static variables)
* The part of the executable which runs between "begin ... end." in the 
main project file is a thread itself (also called "main thread"), so one 
does not need to differentiate between threads started by you and the 
thread started by the operating system at process start
* The Heap (the area of the memory where e.g. object instances and data 
allocated with New/GetMem resides) is shared between all threads. So you 
need to be careful if you create an object in thread A and change it in 
thread B (and thread A as well). But if you create an object in method X 
that is called by thread A and thread B and you never pass the instance 
to another thread you have no problem, because no other thread then 
knows the reference to this object.

I hope this clarifies things a bit. Feel free to ask back if you need to.


More information about the Lazarus mailing list