Wu Adam wrote:
> The TInterfacedObject provides default referencing couting support, 
> which uses Interlocked_ operations that seems to be threadsafe. However, 
> I think there still is a race condition in the following scenario:
> 
> 0. An interface, "IntfA", implemented by a TInterfacedObject descendant 
> has refcount 1;
> 1. A thread, "threadA", makes another reference to 'IntfA', however, the 
> execution is interrupted just before the InterlockedIncrement() in _AddRef;
> 2. Another thread dereferences "IntfA", the instance's refcount drops to 
> 0 and is destroyed.
> 3. Execution of "threadA" resumes, but the instance is no longer there!
> 
> I think I am being paranoid again, and please tell me yes! (otherwise 
> life is going to be very miserable...)

You have a legitimate concern. But here's the problem in your reasoning:

The reference count is meant to count references. It protects the 
object. The reference count does *not* protect the references to that 
object. In your scenario, there are two threads that both have access to 
the apparently global IntfA variable. If two threads have access to the 
same variable, then there are really two references, so the reference 
count should be 2, not 1.

The alternative is that you should use a critical section to protect 
access to the global variable, so you can have one thread reading it 
while another is writing it.

The same goes for global string variables. And these don't necessarily 
have to be global variables, either. They can be fields of an object, as 
long as multiple thread have access to the same fields at the same time.

-- 
Rob
_______________________________________________
Delphi mailing list -> [email protected]
http://www.elists.org/mailman/listinfo/delphi

Reply via email to