This approach is far from perfect, because, as I understand from your code, you have only one lock for the entire application. It is better when each independent data object has its own lock. So you will have an abstract class:
type TAbstractData = class private CriticalSection: TRtlCriticalSection public constructor Create; procedure Lock; procedure Unlock; destructor Destroy; override; end;
Then inherit other classes from this abstract class that implements locking.
constructor TAbstractData .Create; begin inherited Create; InitializeCriticalSection(CriticalSection); end; procedure TAbstractData.Lock; begin EntercriticalSection(CriticalSection); end; procedure TAbstractData.Unlock; begin LeaveSection(CriticalSection); end; procedure TAbstractData.Destroy; begin DeleteCriticalSection(CriticalSection); inherited Destroy; end;
A CriticalSection are the most efficient synchronization classes implemented in Windows so far. It is practically free - it consumes almost no system resources if there is no thread conflict, and does not cause an expensive context switch when only one thread uses data.
After I posted the answer, you found a good article on the Internet - http://blog.synopse.info/post/2016/01/09/Safe-locks-for-multi-thread-applications - the author recommends a similar approach.
source share