Critical sections

The easiest way to explain the use of critical sections is with an example. As the ReadWrite example is still fresh in your mind, I'll return to it. This program implements—in addition to the unsafe reading/writing approach—a code that reads and writes data with additional protection from a critical section lock.

This critical section is created when a form is created, and destroyed when the form is destroyed. There is only one critical section object shared by both threads:

procedure TfrmReadWrite.FormCreate(Sender: TObject);begin  FLock := TCriticalSection.Create;end;procedure TfrmReadWrite.FormDestroy(Sender: TObject);begin  FreeAndNil(FLock);end;

When a reader wants to read from FPValue^, it will firstly acquire the critical ...

Get Mastering Delphi Programming: A Complete Reference Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.