[DUG] A Super Simple Summary of Thread Safe

Kyley Harris KyleyHarris at gmail.com
Mon Jun 20 23:06:05 NZST 2005


A couple of simple things related to some of the conversations going on.

1/ Reading Memory is always threadsafe, unless the memory was freed. If 
you don't use critical sections, you may read the wrong thing, because 
something else overwrote the memory while you are reading it, in full or 
part.
2/ Writing to Memory is not threadsafe, because you are altering the 
memory structure, especially in more complex structures such as lists, 
strings, objects etc. Writing to an integer could be considered 
threadsafe, but it probably depends on the compiler, the computer, the 
stack size, the natural integer size, etc etc.. The Purpose of a 
Critical Section is much like a database transaction, to ensure that 
what you read and write is correct at any given time, and to create a 
hands off approach. if you do lots of reading, with few writes, and need 
speed, use a TMultiReadWriteSyncronizer.

3/ Writing to the VCL GUI controls is only ever safe if the 
CurrentThreadID = MainThreadID. It does not matter if you are reading or 
writing. Why? Most of the controls like TEdit etc are TWinControls. 
TWinControls have a Handle. if you use the handle, or create the handle 
in any thread other than the main one windows will throw silent tantrums 
and simply ruin the stability of your application. This is a design 
issue. Don't expect to find it in the help files, or anywhere really :)

There are plenty more things that you need to do to make sure a GUI 
accessing threaded processing doesn't go down the toilet but I hope this 
helps.

regards
  Kyley.

PS. This may not be 100% semantically accurate, but who has time for 
that in these posts :D



More information about the Delphi mailing list