Is single-threaded assignment of atomic operation on iPhone?

I assume that on a 32-bit device such as the iPhone, assigning a short float is an atomic, thread-safe operation. I want to make sure that 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;
}
+5
source share
3 answers

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

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

Since there are 2 instructions, the CPU is free to do anything between them, but only the second instruction str r0, [r2]affects the memory. If globalFloatnot aligned, the CPU can perform atomic recording with one copy.

, . , , . CGRect.

. - . OSMemoryBarrier() "" .

, (, globalFloat += value). OSAtomic.

+5

, . 32- , 32- (char, short, int, long, float ..), .

+3

There is more to your question than just atomicity. Even if the record is atomic, there is no guarantee that another thread will see the change without any memory barrier. This is probably not a problem with current iPhones because they only have one processor, but it can be a problem on desktop computers.

Cm:

0
source

All Articles