Atomic and mutex lock. Their application in iOS development

Nguyen Tuan Minh
2 min readMay 29, 2021

Atomic and mutex in C

Atomic

According to definition: “Atomic types are types that encapsulate a value whose access is guaranteed to not cause data races and can be used to synchronize memory accesses among different threads.”

Firstly, we should understand “data races”. When an evaluation of an expression writes to a memory location and another evaluation reads or modifies the same memory location, the expressions are said to conflict. A program that has two conflicting evaluations has a data race. When “data races” occurs, the result in invalid.

Atomic assures that read action returns valid value and write action does update the memory. But the order is not assured in normal situations. For example memory X holds value X. At the same time, thread A gets, while thread B writes value B and thread C writes value C. Thread A can get any of the three values X, B, C ( See detail ).

That’s where “synchronize memory access” comes. If memory order specified, atomic can be synchronized, but of course, with slower speed.

Mutex

According to definition “The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.” Similar to atomic, mutex protects the program from multiple threading environments. The main difference is that mutex is “synchronization primitive”.

So with the above analysis, while atomic is faster, mutex assures synchronization. We can use atomic when ordering is not important, while mutex may be better when we have lines of code needed to be protected.

Their application in objective C

Atomicity:

Apple’s old documentation stated that : “If you specify strong, copy, or retain and do not specify nonatomic, then in a reference-counted environment, a synthesized get accessor for an object property uses a lock and retains and autoreleases the returned value”. What we understand here is that an object-type atomic is no different from lock , while primitive-type can still be a true atomic-type. With that in mind, synthesizing atomic properties makes no sense.

Lock

One very common use of iOS development is pthread mutex, which is used directly from C-library. It has all the pros and cons of mutex lock stated above.

Another API Apple provides is os_unfair_lock. It may be faster than pthread_mutex due to its’ unfairness. Fairness means all threads get a chance to acquire lock. os_unfair_lock doesn’t assure that. For instance, a thread after unlocking, can go back and acquire lock again while others waiting.

In conclusion, while pthread_mutex has been proved to be extreme useful, sometimes using atomic or os_unfair_lock brings better performance.

--

--

Nguyen Tuan Minh

iOS developer | Meditator. Be fond of logical and deep research