Can threads safely read variables set by VCL events?

Posted by Tom1952 on Stack Overflow See other posts from Stack Overflow or by Tom1952
Published on 2010-04-08T14:23:06Z Indexed on 2010/04/08 15:03 UTC
Read the original article Hit count: 298

Filed under:
|

Is it safe for a thread to READ a variable set by a Delphi VCL event?

When a user clicks on a VCL TCheckbox, the main thread sets a boolean to the checkbox's Checked state.

CheckboxState := CheckBox1.Checked;

At any time, a thread reads that variable

if CheckBoxState then ...

It doesn't matter if the thread "misses" a change to the boolean, because the thread checks the variable in a loop as it does other things. So it will see the state change eventually...

Is this safe? Or do I need special code? Is surrounding the read and write of the variable (in the thread and main thread respectively) with critical code calls necessary and sufficient?

As I said, it doesn't matter if the thread gets the "wrong" value, but I keep thinking that there might be a low-level problem if one thread tries to read a variable while the main thread is in the middle of writing it, or vice versa.

My question is similar to this one: http://stackoverflow.com/questions/1353096/cross-thread-reading-of-a-variable.

(Also related to my previous question: http://stackoverflow.com/questions/2449183/using-entercriticalsection-in-thread-to-update-vcl-label)

© Stack Overflow or respective owner

Related posts about delphi

Related posts about multithreading