In iOS, atomic just guarantee write/read safe. Not thread safe. Someone said thread safe is a higher level. I confuse about their difference. Does w/r safe sometimes could be used to implement thread safe?
And when atomic cannot guarantee
Thread safe. Why we use it in multiple threads?
2 Answers
As an example, consider a 64-bit long
integer type running on a 32-bit processor. Since the processor only operates with 32 bits at a time, updating the long
looks something like this pseudo-assembly:
mov %r1, [addr]
mov %r2, [addr+4]
If the variable starts with the value of 0 and you try to write 0xffffffff
to it, then it is possible that execution gets interrupted between these two instructions and other code reading the memory reads the value 0x0000ffff
.
An atomic update guarantees that the entire value is written as a single operation, some way or another, so that while (since it's not thread-safe) you aren't guaranteed exactly when another thread will see an updated value, you are guaranteed that whenever it does see a value, it won't be partly updated but will be a completely correct (even if perhaps outdated) value. This concept can be extended to more complex data types where it is relevant.

- 75,269
- 21
- 115
- 152
-
So, it can't ensure thread safe. And atomic could be used as a step to implement thread safe. And thread safe is a higher level, we use locks – showlog Oct 08 '18 at 00:22
atomic guarantees exclusive execution only on a single property, that is, you can't read/write a single property on an object at the same time.
However, atomic doesn't guarantee that two different properties of the same object are exclusively accessed/written to at the same time.
The most common example given to illustrate this is a Person
class with firstName
and lastName
properties.
let person = Person()
// Thread 1
person.firstName = "Name1"
person.lastName = "LastName1"
// Thread 2
person.firstName = "Name2"
person.lastName = "LastName2"
In the worst case, person
could end up being Name1 LastName 2
or Name2 LastName1
.
This is where the higher level thread safety comes into place, I'm using lock/unlock as a placeholder of the platform/language specific locking mechanism.
let person = Person()
// Thread 1
lock(person)
person.firstName = "Name1"
person.lastName = "LastName1"
unlock(person)
// Thread 2
lock(person)
person.firstName = "Name2"
person.lastName = "LastName2"
unlock(person)
With this locking/unlocking, we guarantee that setting firstName
and lastName
on person
are executed together.

- 9,217
- 3
- 42
- 59
-
Yes, from this aspect, thread safe is a higher level about transactions in the program. W/R safe is a common and lower level and doesn't have a relationship with the logical in our program. Is it right? – showlog Oct 08 '18 at 00:31