[Objective C] Generate a crash of race condition and solve.

Initial idea of crash :

  • Multi global thread access to one variable (val) at the same time :
    Write (newVal).
    Then read : Check if val == newVal.
  • Each thread initially sleeps for a random time to create the multiple access randomly. Hopefully, crash comes.

But still. Everything works well. However, working for an app of millions users like Zalo, it is not allowed to use such code. I worked around to find another way to simulate the crash.

What if we do some huge tasks between write and read of val ?

And Crash !

Next step is to choose a suitable solution. Considering mutex_lock and os_unfair_lock, I pick the latter one for its speed.

And No more Assert. The code is protected.

Further research : what is the deep difference behind mutex_lock and os_lock. What mutex_lock sacrificed for it’s speed?

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