[fpc-devel] ref count types / threadsave question

Jonas Maebe jonas at freepascal.org
Wed Jan 2 21:52:59 CET 2019

On 02/01/19 21:46, Martin Frb wrote:
> On 02/01/2019 21:22, Benito van der Zander wrote:
>> Hi,
>> but if another core can do anything to the string, the refcount should 
>> already be 2, one for this core and one for the other core, should it not?
> No:
> // global var
> var
>    Foo: String;
> // main thread
> Foo := getsomestring_with_refcount_1();
> TMyThread.Create(false); // not suspended / start
> Foo := ''; // de-ref
> //TMyThread.Execute
> LocalFoo := Foo; // copy from the global var

This is a different issue. Managed types are indeed only threadsafe as 
long as there is no race condition that could cause their refcount to 
become zero at some point.

The issue I was talking about is the fact that atomic operations do 
function as global memory synchronisation operations across all cores 
(at least not on all architectures). If core 1 atomatically increases 
refcount to two and you "then" load the same refcount normally (without 
an atomic read-modify-exchange oepration) on another core, this other 
core may still see the old value.

The reason "then" is between quotes is because there is no forced 
ordering between these two operations (since there is no 
synchronisation/memory barrier linking the the two), which is also the 
basis of the problem.

See e.g. 
https://homes.cs.washington.edu/~bornholt/post/memory-models.html for 
more information.


More information about the fpc-devel mailing list