checking for equality on dispatch_queue_t

百般思念 提交于 2019-11-29 08:23:40

This depends on the queue you're on. In this particular case use:

if ([NSThread isMainThread]) {}

In general, you can use dispatch_get_current_queue() to test which queue your're on. In that case you can use the == operator to do so. To quote the Dispatch Queues page in Apple's Concurrency Programming Guide:

Use the dispatch_get_current_queue function for debugging purposes or to test the identity of the current queue. Calling this function from inside a block object returns the queue to which the block was submitted (and on which it is now presumably running). Calling this function from outside of a block returns the default concurrent queue for your application.

Since dispatch_get_current_queue() is deprecated, we could compare current and your queues by their labels (or specifics as @jkh suggested)

For label use

dispatch_queue_get_label(dispatch_queue_t queue);

and pass DISPATCH_CURRENT_QUEUE_LABEL for get label of current queue

For specific:

dispatch_queue_get_specific(dispatch_queue_t queue, const void *key);

for get you queue specific and

dispatch_get_specific(const void *key);

for current

It's require to set one or both of label and specific for your queue. For example when you create it

dispatch_queue_create(const char *label, dispatch_queue_attr_t attr);

or using setters for specific

dispatch_queue_set_specific(dispatch_queue_t queue, const void *key,
    void *context, dispatch_function_t destructor);

First part of answer: What are you trying to do? Why do you need to compare queues? If all you need to do is "tag" a queue with some specific piece of metadata, consider using dispatch_queue_{set, get}_specific() instead.

Second part of answer: Don't use dispatch_get_current_queue() for, well, anything. It's just for debugging purposes and its use has always been discouraged.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!