How to handle crashes caused by semaphore in iOS?

Viewed 598

Crashes when the class is destructed, how to handle unfinished semaphore?

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……")
    }
}

EXC_BAD_INSTRUCTION

1 Answers

It crashes because of lack of semaphore.signal() and wrong setup of semaphore.

You should call semaphore.signal() after you are done with the async method.

You should add semaphore.wait() outside of the async method.

In your case, it could be like this;

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……")
}

}
Related