Lock and unlock resources with a single command

I work with threads and that I use mutexes to block shared resources. The basic use of locking is to allocate resources in a lock / unlock block.

procedure RefreshData; begin DataLock; GetData; GetSettings; CheckValues; ... DataUnlock; end; 

Since there is always a Lock / Unlock pair, I started thinking of a simplified lock / unlock approach that would automatically unlock resources when they are no longer needed.

So, my idea was to introduce a new procedure that would take a reference to a use case as an input parameter. This will give me the opportunity to use an anonymous method.

The code will look something like this:

 type TBaseProc = reference to procedure; procedure TMyObject.LockMethod(AMeth: TBaseProc); begin DataLock; try AMeth; finally DataUnlock; end; end; procedure TForm1.RefreshData; begin MyObject.LockMethod( procedure begin GetData; GetSettings; CheckValues; ... end; ); end; 

Does this approach make any sense or is there a better or even simpler solution to this?

Thank you and welcome.

+5
source share
1 answer

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.

0
source

Source: https://habr.com/ru/post/1207290/


All Articles