views:

163

answers:

2

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;
}
+4  A: 

No. In a typical iPhone application, the function above will be compiled to

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

Obviously, a normal 2-instruction code cannot be atomic. But it is atomic in the sense that the value will either be written successfully or completely overridden — unlike assignment to a double, for instance.

Use the OSAtomic functions to ensure the assignment is atomic.

KennyTM
But this is still "kinda sorta atomic", in that the actual write to the global state is a single instruction, so nobody looking at globalFloat can ever see it in an in-between state.
unwind
There isn't one for assignment.
Andreas Bonini
@unwind: that's true of any store instruction. The in-between state here is after it's read and before it's written, when the variable physically exists in two places (memory and register) at once.
Potatoswatter
@Potatoswatter: I don't think so. It's possible to imagine architectures where there's a single instruction that stores a value that is larger than the external data bus. This instruction would need to be split into multiple bus transactions, so if you look at memory it will be partially updated, with intermediate states visible during entire cycles.
unwind
It isn't kind sort atomic. It is completely atomic. The first instruction doesn't interact with the value at all, it just loads its address into r2. @Potatoswatter, the question is not whether the variable exists in two or more places at once (the same can be said of char), but whether the value can be partially written to the memory location by one thread when another thread attempts to read it. This can never happen in the above code.
Marcelo Cantos
@unwind, @Marcelo: I'd be surprised if any native datatype of the iPhone processor takes more than one memory transaction to store. (Double, really?) Atomicity in programming (and most hardware specifications) refers to read-modify-write. You can't synchronize threads without that, and OP asks about threads.
Potatoswatter
+2  A: 

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.

Marcelo Cantos