|Subject:||Re: Cheapest way to protect access of variables from inside a thread and from th|
|Posted by:||Remy Lebeau (TeamB) (firstname.lastname@example.org)|
|Date:||Thu, 6 Oct 2005|
"Ross McMillan" <email@example.com> wrote in message
> The threads are all created and destroyed from the main loop and it
> all seems to work fine. My question - the thread itself updates the
> state and result variables and strings while it runs, but I want to be
> able to display the thread status from the main loop.
Then your thread class should call its Synchronize() method when it wants to
update the main thread each time a value changes. The main thread should
not have to poll the thread instances at all.
> I realise this brings into play the issue of two threads (one being the
> VCL thread) accessing a variable at the same time and I'm wondering
> what is the most convenient way of managing this
If the main thread is the one who is going to access the variables whenever
it wants (which I do not recommend), then there is only one way - wrap each
variable with a synchronization object, such as a critical section, mutex,
> should I create a critical section with each thread and bracket the
> to the variables from within the thread with the CS enter and leave?
That is the way to go, if the main thread is polling the values. If the
thread uses Synchronize() to update the main thread, then you do not need
any synchronization object at all.
> If I do this, do I need to take any steps when accessing the variables
> from the VCL thread?
The main thread would also have to lock/unlock the critical section. A
critical section is useless unless both the main thread and the worker
thread share the same critical section.
> Or are the thread-safe data types likely to be a more conveniet way to go?
All they do is use a critical section internally. Indy does have several
thread-safe classes for various data types, such as integers, strings, etc.
Cheapest way to protect access of variables from inside a thread and from the VC posted by Ross McMillan on Fri, 7 Oct 2005