[fpc-pascal] Thread Safety of String

Jeppe Græsdal Johansen jeppe at j-software.dk
Wed Jun 4 22:03:39 CEST 2014


It will never throw an exception, but it will never be thread safe either.

Unless you are using the Interlocked* functions no datatype is 
threadsafe on a modern processor(except for reference counting of 
ansistrings, dynamic arrays, and interfaces; and all those use 
Interlocked* functions under the hood).

Use semaphores or events instead if you need something fast, thread 
safe, and responsive.

Den 04-06-2014 21:41, md at rpzdesign.com skrev:
> I thought I had publicly declared what I wanted to do.
>
> Here is the example code again for ease of reference:
>
> Type
>    Class TTest(TObject)
>    public
>      nflag : integer ;
>      sflag : string[30]
>    end;
>
>
> Gui Thread
>
> gtest := TTest.Create ;
>
> Thread #1 - Constantly changing values
>
> while true do
> begin
>   gtest.nflag := Random($FFFFFFFF) ;
>   gtest.sflag := inttostr(gtest.nflag) ;
> end;
>
> Thread #2 - Constantly Comparing values
>
> While true do
> begin
>
>    if gtest.nflag = 777888 then
>    begin
>      break ;
>    end;
>
>    //Test string matching instead of integer matching
>    if gtest.sflag = '123456' then
>    begin
>      LaunchSpaceShuttle(gtest) ;
>    end;
>
> end;
>
> Will this code be thread safe in terms of the gtest.sflag = '123456'
> line never throw an exception because it is referring to stable memory
> that is always less than 31 bytes.
>
> Cheers,
>
> marco
>
>
>
> On 6/4/2014 3:27 PM, Mattias Gaertner wrote:
>> On Wed, 04 Jun 2014 15:03:31 -0400
>> "Saunders, Rich" <greymont at mykolab.com> wrote:
>>
>>> [...]
>>> Whether static variables are more or less thread safe is for you to
>>> decide since you know what you are doing with them. I don't think either
>>> short strings or Strings are inherently more or less thread safe. It
>>> depends on what you do with them.
>> No data is "thread safe". Only code can be thread safe.
>>
>> Mattias
>> _______________________________________________
>> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
>> http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
>>
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
>




More information about the fpc-pascal mailing list