When interview was asked, have a bit meng force suddenly, then oneself study to realize

The principle of spin locking

If the shared data has been locked by another thread, the thread will wait for the lock in an infinite loop. Once the accessed resource is unlocked, the thread waiting for the resource will execute immediately.

Analysis of the

  • Infinite loop
  • Wait without sleep
  • Unlock immediately

code

struct LYSpinLock{ var flag = 0 mutating func lock(){ while (self.setFlag() ! = 0) { } } mutating func unlock(){ flag = 0 } private mutating func setFlag()->Int{ if flag == 0{ flag = 1 return 0 }else{ return 1 } } }Copy the code

application

Var spinlock = lyspinlock. init(flag: Global ().async {self.action()} dispatchqueue.global ().async {self.action() action(){ while true { spinlock.lock() if num >= 100{ spinlock.unlock() return } num += 1 print("\(num)----\(Thread.current)") spinlock.unlock() } }Copy the code

The effect