Mega Code Archive

 
Categories / Delphi / Examples
 

How to make a data structure thread-safe

You need to create a global TCriticalSection and lock / unlock it when you access shared resources with code as shown below. Create a separate TCriticialSection instance for each resource that can be used independently. TCriticialSection is defined in unit SyncObjs. uses SyncObjs; // one lock for each independent resource var myLock : TCriticalSection; // early during application startup: myLock := TCriticalSection.Create; procedure TMyThread.Execute; begin //... lock it myLock.Acquire; // use the shared resource // unlock it.. myLock.Release; end;