Lazarus

Free Pascal => General => Topic started by: guest58172 on January 21, 2017, 11:48:24 am

Title: Atomically read/write ?
Post by: guest58172 on January 21, 2017, 11:48:24 am
How do we atomically read or write global variables ?
I've see the Interlocked... family of functions in system.pas but I see nothing to read write, typically when a thread has to access a global (non-TLS, declared as a unit var) variable.
Title: Re: Atomically read/write ?
Post by: Thaddy on January 21, 2017, 03:43:42 pm
How do we atomically read or write global variables ?
I've see the Interlocked... family of functions in system.pas but I see nothing to read write, typically when a thread has to access a global (non-TLS, declared as a unit var) variable.

It depends.On complex types you will need TMultipleReadExclusiveWriteSynchronizer.
Simple,numeric, types are usually safe to read on most platforms. they are atomic for read. At least the native integer/uint and smaller types usually are.
- Caveat: that means that a 64 bit var on a 32 bit system is NOT atomic for read! but it is on a 64 bit system. You have been warned,

To write those simple types, first read them (store thread local), work with them and then use interlockedexchange or better interlockedcompareexchange to write them back.
InterlockedCompareExchange is the one I use most. After all, another thread may have put in the same value. If it is already equal - the comparison is also atomic - there's no point in writing a new value.
Code: Pascal  [Select][+][-]
  1. {$macro on}
  2. {$Define WriteIfChanged := InterlockedCompareExchange}
TinyPortal © 2005-2018