delphidelphi-2009critical-section

Delphi TCriticalSection Acquire vs Enter - what is the difference?


I am updating Delphi (Delphi 2009) code which uses exclusively TCriticalSection.Acquire/Release pairs, not Enter/Release or Leave pairs. My question is - what is the difference between Acquire and Enter?

Delphi documentation is quite obscure - it even tries to say, that there is no difference:

http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/!!MEMBERTYPE_Methods_SyncObjs_TCriticalSection.html

Acquire: Binds the critical section to the calling thread. Call Acquire to block all other threads from acquiring this critical section until the Release or Leave method is called. Acquire does the same thing as the Enter method.

Enter: Blocks other threads when the calling thread enters a thread-sensitive section. Call Enter to block all other threads from entering code protected by this critical section until the Leave or Release method is called. Enter calls the Acquire method to bind the critical section to the calling thread.

I would like to have the method TryAcquire, but there is no such method, so - I am considering to replace all my calls to Acquire with TryEnter... Sleep... loop, that is bounded by the number of TryEnter calling efforts. But to be sure what will hapen, I should know the distinction between Acquire and Enter? What is this distinction? Why two different methods?


Solution

  • For TCriticalSection there is no difference. Enter is implemented as a call to Acquire. Likewise for Leave which is implemented as a call to Release.

    The TryEnter method was added after Delphi 2009. But it's just a simple wrapper around the Windows API call TryEnterCriticalSection. You can call that function directly yourself. You could, for example, use a class helper to introduce TryEnter into the scope of TCriticalSection.