[fpc-devel] ref count types / threadsave question
n-a-zhubr at yandex.ru
Thu Jan 3 14:58:15 CET 2019
03.01.2019 15:25, Benito van der Zander:
> The ref count is stored in the same memory block as the string itself.
> If core 2 could not see the new ref count, it could not see what is in
> the string and thus not use the string for anything .
If string content modification is supposed to be possible and the said
string is accessible by 2 or more threads, then some sort of explicite
syncronization will need to be used (like with many other cases of data
sharing across multiple threads). Pascal does not provide complete
automatic thread-safety for strings (AFAIK). It does provide automatic
lifecycle management (refcounting) only.
> Am 02.01.19 um 21:52 schrieb Jonas Maebe:
>> On 02/01/19 21:46, Martin Frb wrote:
>>> On 02/01/2019 21:22, Benito van der Zander wrote:
>>>> 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?
>>> // global var
>>> Foo: String;
>>> // main thread
>>> Foo := getsomestring_with_refcount_1();
>>> TMyThread.Create(false); // not suspended / start
>>> Foo := ''; // de-ref
>>> 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.
>> fpc-devel maillist - fpc-devel at lists.freepascal.org
>> <mailto:fpc-devel at lists.freepascal.org>
> fpc-devel maillist - fpc-devel at lists.freepascal.org
More information about the fpc-devel