I have a method which should support being called from any queue, and should expect to.
It runs some code in a background thread itself, and then uses dispatch
Based on the source from SQLite.swift.
If you want to check whether you're on own special dispatch queue:
class Worker {
private static let queueKey = DispatchSpecificKey()
private lazy var queueContext = unsafeBitCast(self, to: Int.self)
private lazy var queue: DispatchQueue = {
let value = DispatchQueue(label: "com.example.App.Worker")
value.setSpecific(key: Worker.queueKey, value: queueContext)
return value
}()
func test(x: Int) -> Int {
return dispatchSync {
return x > 2 ? test(x: x - 1) * x : x
}
}
private func dispatchSync(_ block: () throws -> T) rethrows -> T {
if DispatchQueue.getSpecific(key: Worker.queueKey) != queueContext {
return try queue.sync(execute: block)
}
return try block()
}
}
let worker = Worker()
worker.test(x: 5)