Translate

2009/02/19

Using critical sections

話說BCB在執行緒中有同步的指令,但這是應用在VCL元件上面,在不用到VCL的埸合時,我們就可以利用「Critical Sections」來對多執行緒做排序處理,以下是從BCB的help中節錄出來的:

If objects do not provide built-in locking, you can use a critical section. Critical sections work like gates that allow only a single thread to enter at a time. To use a critical section, create a global instance of TCriticalSection. TCriticalSection has two methods, Acquire (which blocks other threads from executing the section) and Release (which removes the block).

Each critical section is associated with the global memory you want to protect. Every thread that accesses that global memory should first use the Acquire method to ensure that no other thread is using it. When finished, threads call the Release method so that other threads can access the global memory by calling Acquire.

Warning: Critical sections only work if every thread uses them to access the associated global memory. Threads that ignore the critical section and access the global memory without calling Acquire can introduce problems of simultaneous access.

For example, consider an application that has a global critical section variable, pLockXY, that blocks access to global variables X and Y. Any thread that uses X or Y must surround that use with calls to the critical section such as the following:
pLockXY->Acquire(); // lock out other threads
try
{
  Y = sin(X);
}
__finally
{
  pLockXY->Release();
}

沒有留言:

張貼留言

Delphi in Web Development: WebBroker + EasyUI (01)

I have been received many demand about web development for long time. But, I don't wont to use ASP.NET develop the web project. M...