Get current dispatch queue?

后端 未结 11 1297
难免孤独
难免孤独 2020-12-23 16:28

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

11条回答
  •  情深已故
    2020-12-23 16:59

    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)
    

提交回复
热议问题