Recent

Author Topic: Atomically read/write ?  (Read 1512 times)

Basile-B

  • Sr. Member
  • ****
  • Posts: 457
Atomically read/write ?
« 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.

Thaddy

  • Hero Member
  • *****
  • Posts: 9278
Re: Atomically read/write ?
« Reply #1 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}
« Last Edit: January 21, 2017, 04:04:31 pm by Thaddy »
also related to equus asinus.