When an object that contains a semaphore gets automatically deallocated by ARC in my app, I get an EXC_BREAKPOINT or an EXC_BAD_INSTRUCTION with the message "BUG IN CLIENT OF LIBDISPATCH: Semaphore object deallocated while in use". The call stack shows libdispatch.dylib`_dispatch_semaphore_dispose.cold.1 as the location of the crash. I noticed that this error doesn't occur when the semaphore's wait/signal calls are balanced such that the semaphore's counter is at the value I initially passed in (see code below). In my actual code (which is in Metal rendering code that's getting called every frame), I don't know what the semaphore's counter is at at any given moment (and because of the abstraction of a semaphore, I shouldn't have to know what the counter is at), so how do I make sure that the object that holds the semaphore (and the semaphore itself) is deallocated properly so I don't get this crash on deallocation?
class Test {
var semaphore = DispatchSemaphore(value: 3)
}
var test = Test()
// will not crash
test.semaphore.wait(timeout: DispatchTime.distantFuture)
test.semaphore.signal()
test = Test()
// will crash
test.semaphore.wait(timeout: DispatchTime.distantFuture)
test = Test()
Seen the discussion on that 'bug' here?
https://lists.apple.com/archives/cocoa-dev/2014/Apr/msg00483.html