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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With