Avoid access at the same time
In order to avoid conflicts with other threads in accessing a global object variable, you need to lock the execution of other threads when performing thread code until the operation is completed. VCL supports three technologies to achieve this:
(1) Lock the object: Some objects are locked, such as Canvas
(2) Using the Critical area
If the object does not improve the built-in lock function, you need to use the Critical area, and the Critical area is only one thread in the same time. In order to use the Critical area, an example of a TCRITICATIONGSECTION is produced. TcriticalSection has two methods, ACQUIRE (prevent other threads from performing this area) and Release (cancel blocking)
Each Critical area is associated with the global memory you want to protected. Each thread access to global memory must first use acquire to ensure that there is no other thread to use it. After completion, the thread calls the Release method, allowing other threads to use this global memory by calling acquire.
WARNING: The Critical District only uses it in all threads to access global memory, if there is a thread calls memory directly, not through Acquire, will cause simultaneous access issues. For example: Lockxy is a global critical zone variable. Any thread that accesses the global x, y, must use acquire before accessing
Lockxy.acquire; {Lock Out Other Threads}
Try
Y: = sin (x);
Finally
Lockxy.release;
END;
(3) Using Multi-Read Exclusive-Write Synchronizer
When you use the Critical area to protect global memory, only one thread is allowed to use this memory in the same time. This may exceed your requirements, especially for objects or variables written frequently. In the multi-thread, when there is no thread writes the same memory, it is not any problem at the same time. When you have some global variables to read frequently, you can use TmultireadexClusiveWritSynchronizer to protect them. This object is like critical section, but when memory is not a thread, allowing multiple threads to read a memory.
In order to use Multi-Read Exclusive-Write Synchronizer, a global TmultireAdexClusiveWriteSynchronizer instance is generated, associated with memory you want to protect. Each thread If you read the memory, you must call the BeginRead method first. It is believed that there is no other thread to write memory. After reading, call the endread. When writing memory, call BeginWrite, then call the endwrite.
WARNING: Like critical section, Multi-Read Exclusive-Write Synchronizer is only valid when all threads use it to access the same global memory. Access to this memory directly will result in simultaneous access issues.
Excerpt from:
Http://www.yesky.com/20000319/35322.shtml