How to get the current queue name in swift 3

前端 未结 6 921
遇见更好的自我
遇见更好的自我 2020-12-23 21:52

We have function like this in swift 2.2 for printing a log message with the current running thread:

func MyLog(_ message: String) {
    if Thread.isMainThre         


        
6条回答
  •  一整个雨季
    2020-12-23 22:40

    Here's a wrapper class that offers some safety (revised from here):

    import Foundation
    
    /// DispatchQueue wrapper that acts as a reentrant to a synchronous queue;
    /// so callers to the `sync` function will check if they are on the current
    /// queue and avoid deadlocking the queue (e.g. by executing another queue
    /// dispatch call). Instead, it will just execute the given code in place.
    public final class SafeSyncQueue {
    
        public init(label: String, attributes: DispatchQueue.Attributes) {
            self.queue = DispatchQueue(label: label, attributes: attributes)
            self.queueKey = DispatchSpecificKey()
            self.queue.setSpecific(key: self.queueKey, value: QueueIdentity(label: self.queue.label))
        }
    
        // MARK: - API
    
        /// Note: this will execute without the specified flags if it's on the current queue already
        public func sync(flags: DispatchWorkItemFlags? = nil, execute work: () throws -> T) rethrows -> T {
            if self.currentQueueIdentity?.label == self.queue.label {
                return try work()
            } else if let flags = flags {
                return try self.queue.sync(flags: flags, execute: work)
            } else {
                return try self.queue.sync(execute: work)
            }
        }
    
        // MARK: - Private Structs
    
        private struct QueueIdentity {
            let label: String
        }
    
        // MARK: - Private Properties
    
        private let queue: DispatchQueue
        private let queueKey: DispatchSpecificKey
    
        private var currentQueueIdentity: QueueIdentity? {
            return DispatchQueue.getSpecific(key: self.queueKey)
        }
    
    }
    

提交回复
热议问题