3

Lets say I have an application that is writing to a boolean from one thread and reading from the same boolean from another thread.

I don't care if my reading thread reads a stale value. Is this safe on all ARM cores and x86? I don't want to run into an issue were a partially written value is read by my reading thread.

Follow up question: Which swift types have guaranteed atomic reads and writes on x86 and ARM?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
FreaknBigPanda
  • 1,127
  • 12
  • 17
  • On x86, [naturally-aligned loads/stores](http://stackoverflow.com/questions/36624881/why-is-integer-assignment-on-a-naturally-aligned-variable-atomic/36685056) of up to 64bits are atomic. So unless Swift does something perverse (like use an unaligned 32bit value), then yes, they're atomic. For a boolean, "tearing" probably doesn't even matter, because the upper bits of true and false are both zero. (Unless Swift stores booleans as 0 / -1 (all-ones)?) – Peter Cordes Jun 21 '16 at 04:33
  • And the same is true for ARM (note, there are 64-bit and 32-bit ARM cores). I do not think Swift or any other language has anything to do with this, it's all down to CPU load/store instructions. – tum_ Jun 21 '16 at 06:57
  • @A.Toumantsev It's absolutely to do with Swift, because it's a question of which of those underlying machine types the language ABI chooses to implement the higher-level types with. – Notlikethat Jun 21 '16 at 07:51
  • @Notlikethat I'll shut up, then, as I know nothing about Swift. :) – tum_ Jun 21 '16 at 08:05
  • @FreaknBigPanda don't rely on this, it seems fragile and poorly designed. Stick to established multi-threading the IPC techniques. – Alexander Jun 21 '16 at 15:05
  • Does Apple really not talk about Swift variable atomicity anywhere? They do for ObjC, which has that `atomic` keyword. All I can find on Swift is the low-level APIs. – sudo Jul 24 '18 at 21:10

0 Answers0