iOS中semaphore引起的crash如何处理?

How to handle crashes caused by semaphore in iOS?

class销毁时崩溃,如何处理未完成的信号量?

class CrashTestViewCtrl: UIViewController {

    private var semaphore = DispatchSemaphore(value: 2)

    override func viewDidLoad() {
        super.viewDidLoad()
        
        DispatchQueue.global().async { [weak self] in
            self?.semaphore.wait()
            // do something ......
        }
    }
    
    deinit {
        print("……deinit……")
    }
}

由于缺少 semaphore.signal() 和错误的信号量设置而崩溃。

您应该在完成异步方法后调用 semaphore.signal()

您应该在异步方法之外添加 semaphore.wait()

你的情况可能是这样的;

class CrashTestViewCtrl: UIViewController {

private var semaphore = DispatchSemaphore(value: 2)

override func viewDidLoad() {
    super.viewDidLoad()
    
    DispatchQueue.global().async { [weak self] in
        
        // do something ......
        self?.semaphore.signal()
    }
    
    semaphore.wait()
}

deinit {
    print("……deinit……")
}

}