Reputation: 18171
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?
Upvotes: 2
Views: 148
Reputation: 596397
When it comes to databases, most database components are not thread-safe unless you use database sessions. It is usually better to give each thread its own connection to the database instead and not share connections or components across thread boundaries.
Upvotes: 0
Reputation: 16612
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.
Upvotes: 8
Reputation: 24857
Use some kind of inter-thread comms to signal a message from B to A to write data to the DB. This keeps DB access to one thread. Exact mechanism depends on how thread B normally gets its inputs, (how does it?).
Upvotes: 1
Reputation: 4776
You can use critical sections to prevent simultaneous access to memory.
Upvotes: 2