checking for equality on dispatch_queue_t

和自甴很熟 提交于 2019-12-29 07:15:12

问题


How can I check for equality between dispatch_queue_t vars?

dispatch_queue_t currentQueue = dispatch_get_current_queue();
dispatch_queue_t mainQueue = dispatch_get_main_queue();
if (currentQueue == mainQueue) {

}

from the docs:

typedef struct dispatch_queue_s *dispatch_queue_t;

I'm not sure but does this mean that it's a pointer to a dispatch_queue_s struct?

Since I can't check equality on pointers, I'm not sure how can I check if a dispatch_queue_t is the same as another?


回答1:


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.




回答2:


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);



回答3:


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.



来源:https://stackoverflow.com/questions/12606158/checking-for-equality-on-dispatch-queue-t

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