Skip to content

Commit

Permalink
Fix "Semaphore object deallocated while in use"-crash 🤞 (#4)
Browse files Browse the repository at this point in the history
* Fix "Semaphore object deallocated while in use"-crash 🤞

* Fix the initial value as well

(this has no practical impact, I just want to avoid having DispatchSemaphore(value:1) anywhere in the code)
  • Loading branch information
melle committed Apr 20, 2021
1 parent f1293f0 commit e3029a5
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions Sources/CombineLongPolling/LongPollingPublisher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ extension LongPollingPublisher {
private var started = false
private var finished = false
private var currentRequest: AnyCancellable?
private var semaphore = DispatchSemaphore(value: 1)
private var semaphore = DispatchSemaphore(value: 0)

init(dataTaskPublisher: AnyPublisher<(data: Data, response: URLResponse), URLError>, subscriber: S) {
self.dataTaskPublisher = dataTaskPublisher
Expand Down Expand Up @@ -83,7 +83,11 @@ extension LongPollingPublisher {
}

private func start() {
self.semaphore = DispatchSemaphore(value: 1)
// Instead of creating the semaphore with value 1, we signal() immediately to increase the value to 1. This workaround fixes the
// "Semaphore object deallocated while in use"-crash. See https://lists.apple.com/archives/cocoa-dev/2014/Apr/msg00485.html
// Seal of approvoal: "Greg Parker stated that it’s a feature, not a bug" 🦭
self.semaphore = DispatchSemaphore(value: 0)
self.semaphore.signal()
startPolling()
}

Expand All @@ -94,6 +98,7 @@ extension LongPollingPublisher {
self.lock.lock()
return self.started && !self.finished
}() ) {
// on the first run, the semaphore is 1, so we are not blocked here and fetch the data immediately.
self.semaphore.wait()

self.currentRequest = self.dataTaskPublisher
Expand Down

0 comments on commit e3029a5

Please sign in to comment.