Question

I read that nonatomic and atomic both are thread unsafe. but nonatomic is faster because it allows faster access means asynchronously and atomic is slower it allows slower access synchronously.

Was it helpful?

Solution

An atomic property in Objective C guarantees that you will never see partial writes.

That is, if two threads concurrently write values A and B to the same variable X, then a concurrent read on that same variable will either yield the initial value of X, or A or B. With nonatomic that guarantee is no longer given. You may get any value, including values that you never explicitly wrote to that variable.

The reason for this is that with nonatomic, the reading thread may read the variable while another thread is in the middle of writing it. So part of what you read comes from the old value while another part comes from the new value.

The comment about them both being thread-unsafe refers to the fact that no additional guarantees are given beyond that. Apple's docs give the following example here:

Consider an XYZPerson object in which both a person’s first and last names are changed using atomic accessors from one thread. If another thread accesses both names at the same time, the atomic getter methods will return complete strings (without crashing), but there’s no guarantee that those values will be the right names relative to each other. If the first name is accessed before the change, but the last name is accessed after the change, you’ll end up with an inconsistent, mismatched pair of names.

A purist might argue that this definition of thread-safety is overly strict. Technically speaking, atomic already takes care of data races and ordering, which is all you need from a language designer's point of view.

From an application-logic point of view on the other hand the aforementioned first-name-last-name example clearly constitutes a bug. Additional synchronization is required to get rid of the undesired behavior. In this application-specific view the class XYZPerson is not thread-safe. But here we are talking about a different level of thread-safety than the one that the language designer has.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top