Get current dispatch queue?

2020-02-17 16:39发布

问题:

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_get_main_queue when it returns a value to its block argument.

I don't want it to force it onto the main queue if it wasn't when it entered the method. Is there a way to get a pointer to the current dispatch queue?

回答1:

You do have the option of "dispatch_get_current_queue()", however the iOS 6.1 SDK defines this API with these disclaimers:

"Recommended for debugging and logging purposes only:"

and

"This function is deprecated and will be removed in a future release.".

Here's another related question with some alternatives you can consider if you want code that's future-proof.



回答2:

With the deprecation of dispatch_get_current_queue() there is effectively no way to know what queue you're executing on. If you peruse the GCD sources, you'll eventually see that this is because there may be multiple answers to the question "what queue am I executing on?" (Because queues eventually target one of the global queues, etc.)

If you want to guarantee that a future block is run on a specific queue, then the only way is to make your API accept a queue as a parameter along with the completion block. This lets the caller decide where the completion gets executed.

If simply knowing whether the caller is on the main thread or not is enough, you can use +[NSThread isMainThread] to find out. In the common case, all blocks executing on the main GCD queue will be executing on the main thread. (One exception to this rule is if your application uses dispatch_main() in lieu of a main run loop, you will have to use dispatch_get_specific and friends to detect with certainty that you are executing on the main queue -- this is a comparatively rare circumstance.) More commonly, note that not all code that executes on the main thread executes on the main queue via GCD; GCD is subordinate to the main thread runloop. For your specific case it sounds like that might be enough.



回答3:

If you are working with an NSOperationQueue, it can provide the current dispatch queue for you.

NSOperationQueue has the class function [NSOperationQueue currentQueue], which returns the current queue as a NSOperationQueue object. To get the dispatch queue object you can use [NSOperationQueue currentQueue].underlyingQueue, which returns your currrent queue as a dispatch_queue_t.

Swift 3:

if let currentDispatch = OperationQueue.current?.underlyingQueue {
    print(currentDispatch)
}

- works for main queue!



回答4:

With the deprecation of dispatch_get_current_queue() you cannot directly get a pointer to the queue you are running on, however you do can get the current queue's label by calling dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) and that does give you some flexibility.

You can always check if you are on that specific queue just by comparing their labels, so in your case if you don't want to force it on main queue, when you entered the method you can just utilize the following flag:

let isOnMainQueue = (dispatch_queue_get_label(dispatch_get_main_queue()) == dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))

If you are running on the global queue, you will respectfully get the queue's label associated with it's QOS type, which can be one of the following:

com.apple.root.user-interactive-qos //qos_class_t(rawValue: 33)
com.apple.root.user-initiated-qos   //qos_class_t(rawValue: 25)
com.apple.root.default-qos          //qos_class_t(rawValue: 21)  
com.apple.root.utility-qos          //qos_class_t(rawValue: 17)
com.apple.root.background-qos       //qos_class_t(rawValue: 9) 

And then you can use dispatch_get_global_queue(qos_class_self(), 0) which will give you back that same global queue you are running on.

But I believe Apple particularly discourages us from bounding the logic to the queue we got called on, so better utilising this for exclusively debugging purposes.



回答5:

There is actually still a way to compare the queue.

When you set up your queue, make sure that you add the label. For my purposes, I have a shared queue that is used for accessing a database to prevent database locking. In my DB.m file I have defined the shared queue function like:

const char *kTransactionQueueLabel = "DB_TRANSACTION_DISPATCH_QUEUE";

+ (dispatch_queue_t)sharedDBTransactionQueue {
    static dispatch_queue_t sharedDBQueue = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedDBQueue = dispatch_queue_create(kTransactionQueueLabel, DISPATCH_QUEUE_SERIAL);
    });

    return sharedDBQueue;
}

The shared db transaction queue is used locally in the file to dispatch all executions to the database. However, there is also a public accessor on this to allow dispatching entire transactions to the database. So internally, if a DB access method is called from within the transaction queue, we need to dispatch internally on a different queue (all synchronous dispatches). So internally, I always dispatch on the proper queue by using the below getter.

/**
 * @description Decide which queue to use - if we are already in a transaction, use the internal access queue, otherwise use the shared transaction queue.
 */
- (dispatch_queue_t)getProperQueueForExecution {
    const char *currentLabel = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL);
    dispatch_queue_t sharedAccessQueue = [DB sharedDBTransactionQueue];
    if (strcmp(currentLabel, kTransactionQueueLabel) == 0) {
        sharedAccessQueue = [DB sharedInternalDBAccessQueue];
    }

    return sharedAccessQueue;
}

Hopefully this helps. Sorry for the long example. The Gist of it is that you can use

const char *currentLabel = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL);

to get the label of the current queue and compare to a defined label.



回答6:

As an alternative approach to this NSOBject's method performSelector:withObject:afterDelay: dispatches the call on the current thread's run loop. According to the docs:

This method sets up a timer to perform the aSelector message on the current thread’s run loop.

Obviously I'm suggesting using this with a delay of zero, which, according to the docs again:

Specifying a delay of 0 does not necessarily cause the selector to be performed immediately. The selector is still queued on the thread’s run loop and performed as soon as possible.

Unfortunately it requires exactly one argument, so some workarounds might be needed if your method takes more or less.

One other thing I noted is that this method is not available for protocols, but implementations alone. This is due to this method living in an NSObject category, and not in the NSObject interface (see PS below). This can easily be fixed by casting to id.

PS: Two different NSObjects exist, a protocol and an implementation. Notice NSObject declaration:

@interface NSObject <NSObject> { ... }

It might seem odd, but one is being declared (after @interface) and the other one is a previously declared protocol (between < and >). When declaring a protocol that extends NSObject (ie., @protocol Foo <NSObject>) the protocol inherits the methods from the later, but not the former. Eventually the protocol is implemented by some class that inherits from the NSObject implementation, so all instances inheriting from the NSObject implementation still holds. But I'm getting off topic.



回答7:

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<Int>()
    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<T>(_ 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)


回答8:

I have the same functional requirements the original post mentions. You should be able to call this async function on any queue, but if called on the main queue, then callback to the user on the main queue. I simply handle it like so:

// cache value for if we should callback on main queue
BOOL callbackOnMT = [NSThread isMainThread];

// ...
// ... do async work...
// ...

if (callbackOnMT && ![NSThread isMainThread]){
    dispatch_async(dispatch_get_main_queue(), ^{
        // callback to user on main queue
        // as they called this function on main queue
        callbackToUser();
    });
}
else{
    // callback to user on our current queue
    // as they called this function on a non-main queue
    callbackToUser();
}


回答9:

To get the label of the current queue and compare to a defined label using.

let queueName = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)