Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two (not main) thread synchronisation

I have two threads (A and B) + one main thread (C) running. Thread A contains an object that is used for writing to the database. Sometimes Thread B also wants to write to the database.

As I understood for this reason I must create synchronization between thread A and B. If I use Synchronize method in thread B it will do synchronization with main thread C, but not with A. How to deal in this situation?

like image 463
vico Avatar asked Jul 29 '26 02:07

vico


1 Answers

This is best integrated into the shared service or resource so that both threads do not need to know of each other. Pseudocode:

uses
  SyncObj;

TSomeService = class
private
  FLock : TCriticalSection;
public
  constructor Create;
  destructor Destroy; override;
  procedure UseService;
end;

constructor TSomeService.Create;
begin
FLock := TCriticalSection.Create;
end;

destructor TSomeService.Destroy;
begin
FreeAndNil (FLock);
end;

procedure TSomeService.UseService;
begin
FLock.Enter;
try
  // ...
finally
  FLock.Leave;
 end;

This is completely transparent to both threads, so both threads can just call

FSomeService.UseService;

without bothering with synchronization.

like image 94
jpfollenius Avatar answered Aug 01 '26 13:08

jpfollenius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!