[fpc-devel] Safely shareable objects
Andrew Brunner
andrew.t.brunner at gmail.com
Sat Jul 2 04:45:56 CEST 2011
2011/7/1 Hans-Peter Diettrich <DrDiettrich1 at aol.com>:
> Adem schrieb:
>>
>> Why each and every object? I thought (b)locking only those touched in
>> the Attach() procedure (9 nodes, in my ) would be sufficient; wouldn't it?
Each and every element in the collection may prove difficult to
protect for a general purposing. This threadsafe list would be able
to use it only one thread owns the list and uses the list in its own
execution thread. For general thread-safe usage any read or write
access to Item.Next,Item.Previous would need to be done within the
scope of the lock itself to avoid corruption. Restricing general
access to Item.Next, or Item.Previous would also prove
counter-productive.
> The more objects with indiviual locks are used together, the higher the risk
> of deadlocks (exponential increase?)
I don't think anyone would suggest that in real-world design - it's
just expected outcome - for describing protection required.
I personally don't use interfaces. I would create items as Objects
with getters/setters to Item.Next and Item.Previous et al could be
accomplished by declaring attributes as property, and thus read and
write would simply request the lock and establish a complex mechanism
for either read barrier or write. Performance wouldn't be ideal but
items would be completely protected.
TDLList=class()
private
FLock:TRTLCriticalSection;
end;
TDLLItem=class()
private
FNext: TDLLItem;
FPrev: TDLLItem;
private
function getNextItem:TItem;
public
constructor Create(aOwner:TDLList); reIntroduce;
public
property Next:TItem; read getNextItem;
end;
function TDLLItem.getNextItem():TDLLItem;
begin
EnterCriticalSection(FOwner.FLock);
Try
Result:=FNext;
Finally
LeaveCriticalSection(FOwner.FLock);
end;
end;
After just think about the above code, you can see things aren't that
simple with the DLL. Even if Next,Prev reads are protected, Another
thread could come in there and request the item be deleted/destroyed.
Thread
More information about the fpc-devel
mailing list