[fpc-devel] ref count types / threadsave question
jonas at freepascal.org
Wed Jan 2 21:44:39 CET 2019
On 02/01/19 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?
The problem is that the different cores may see different values. Core 1
could see that the refcount is 1 (wrong) while core 2 could see that is
2 (correct) unless you add memory barriers (directly, or indirectly by
using atomic read-modify-write instructions).
> UniqueString has such a test:
> Function fpc_ansistr_Unique(Var S : Pointer): Pointer; [Public,Alias :
> 'FPC_ANSISTR_UNIQUE']; compilerproc; inline;
> Make sure reference count of S is 1,
> using copy-on-write semantics.
> pointer(result) := pointer(s);
> If Pointer(S)=Nil then
> if PAnsiRec(Pointer(S)-AnsiFirstOff)^.Ref<>1 then
This function is indeed not threadsafe (and it cannot be made 100%
threadsafe, although it could be made a bit safer —and slower— by
changing the check into an atomic inc/decrement with 0 and checking that
the result is 1).
More information about the fpc-devel