Spin-locking principle: 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 the lock immediately.

Main features of spin locks

1. Continuously obtain the lock status 2. Wait until the lock does not sleep 2

*/ struct XZCSpinLock {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

} /** Class SpinLockViewController: UIViewController {

Var spinLock = xzcspinlock. init(flag: 0) override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .red testSpinLock() // Do any additional setup after loading the view. }Copy the code

/** Two asynchronous threads to execute */

func testSpinLock() { DispatchQueue.global().async { self.action() } DispatchQueue.global().async { self.action() } } Func action(){var num = 0 while spinlock. flag == 0{spinlock. lock() if num >= 100{spinlock. unlock() return} num += 1 print("\(num)----\(Thread.current)") spinLock.unlock() } }Copy the code

Execution result: the screen is a little small, truncated incomplete.