[fpc-devel] ref count types / threadsave question

Martin fpc at mfriebe.de
Wed Jan 2 20:08:42 CET 2019


Below is for ansistring, but same should apply to dyn arrays.

Procedure fpc_AnsiStr_Incr_Ref (S : Pointer); 
[Public,Alias:'FPC_ANSISTR_INCR_REF'];  compilerproc; inline;
Begin
   If S=Nil then
     exit;
// anytime after this line:
// other thread, and only ref-count holder calls fpc_ansistr_decr_ref
// and finishes before "inclock" gets the lock  => so memory gets freed
   If PAnsiRec(S-AnsiFirstOff)^.Ref<0 then exit;
   inclocked(PAnsiRec(S-AnsiFirstOff)^.Ref);
end;

what happens if another thread holds the only reference to the string 
(ref count = 1), and the other thread calls and finishes 
fpc_ansistr_decr_ref before inclocked reaches the point where it 
actually gets the lock?
In that case the memory holding the ref-count would be freed, before 
inclock acquires the lock?

----------
What I was actually thinking off was an potential optimization proposal.

If a local string var has a refcount of 1, then it can not be accessed 
by any other thread. Therefore it needs no lock for decreasing the ref.

- The only one ref has to be hold by the current thread
- Since it is a local var no other thread can see the identifier, and 
therefore this var can not be inside a fpc_AnsiStr_Incr_Ref in another 
thread

You could have a pointer (no ref count) to the string, but passing that 
to another thread would be unsafe anyway, and not get anymore unsafe by 
such a change.

This



More information about the fpc-devel mailing list