Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is single float assignment an atomic operation on the iPhone?

I assume that on a 32-bit device like the iPhone, assigning a short float is an atomic, thread-safe operation. I want to make sure it is. I have a C function that I want to call from an Objective-C thread, and I don't want to acquire a lock before calling it:

void setFloatValue(float value) {
    globalFloat = value;
}
like image 453
iter Avatar asked Mar 31 '10 06:03

iter


3 Answers

In 32-bit ARM, the function above will be compiled to

ldr r2, [pc, #0x??]  ; to retrieve the address of globalFloat
str r0, [r2]         ; store value into globalFloat

As there are 2 instructions, and the CPU is free to perform anything between them, but only the second instruction str r0, [r2] affects memory. Unless globalFloat is unaligned, the CPU can perform single-copy atomic write to it.

The assignment can be non-atomic when the global pointer is unaligned. It is also non-atomic if you are writing to a larger structure e.g. CGRect.

Being atomic is not enough for thread safety. Due to caching and instruction reordering, your change may not be visible to other CPU cores. You may need to insert an OSMemoryBarrier() to "publish" the change.

Atomic operations are usually interesting when it involves compound operations (e.g. globalFloat += value). You may want to check out the built-in OSAtomic library for it.

like image 81
kennytm Avatar answered Nov 15 '22 06:11

kennytm


Yes, it will be atomic. On a 32-bit architecture, any store operation on a primitive datatype that is 32-bits or smaller (char, short, int, long, float, etc.) will be atomic.

like image 26
Marcelo Cantos Avatar answered Nov 15 '22 05:11

Marcelo Cantos


There is more to your question than just atomicity. Even if a write is atomic, there is no guarantee that another thread will see the change without some kind of memory barrier. This probably isn't a problem with current iPhones because they only have one cpu, but it can be a problem on desktop machines.

See:

  • C++ and the Perils of Double-Checked Locking in DDJ (PDF)
  • Memory Barriers
  • StackOverflow discussion on thread data sharing
like image 43
EricS Avatar answered Nov 15 '22 07:11

EricS