swift 关于多线程互斥锁(卖票为例)

上代码

import UIKit

class ViewController: UIViewController {
    
    var tickets = 100
    var theardA:Thread?
    var theardB:Thread?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        theardA = Thread.init(target: self, selector: #selector(sale), object: nil)
        theardA?.name = "A窗口"
        theardB = Thread.init(target: self, selector: #selector(sale), object: nil)
        theardB?.name = "B窗口"
        
    }
    
    @objc func sale () {
        
        for i in 1...100 {
            
            buyTicket(username: "person\(i)")
        }
    }
    
    //开始买票
    @IBAction func begain(_ sender: UIButton) {
        
        theardA?.start()
        theardB?.start()
        
    }
    
    ///objc_sync_enter(lockString)
    ///objc_sync_exit(lockString)
    
    func buyTicket(username: String) {
        
        Thread.sleep(forTimeInterval: 0.5)
        
        ///加上互斥锁,保护资源 同一时刻只能被一个线程读写
        objc_sync_enter(self)
        
        self.tickets -= 1
        
        let currentName = Thread.current.name! as String
        
        print("\(username)在\(currentName)买了一张票,剩余票数:\(self.tickets)")
        
        objc_sync_exit(self)
    }
    
    
    
}

WechatIMG9.png

你可能感兴趣的:(swift 关于多线程互斥锁(卖票为例))