Is this the right way to compare two GCD Queues?

淺唱寂寞╮ 提交于 2019-12-11 03:58:14

问题


Following an earlier question on SO, I'm now looking to compare two different grand central dispatch queues to try and determine if the current code is being run on the main thread or not. My question simply: is this a valid way of achieving this? Or are there some pitfalls of doing this that I haven't considered?

if (dispatch_get_current_queue() != dispatch_get_main_queue()) {

    // We are currently on a background queue

} else {

    // We are on the main queue
}

Cheers


回答1:


Comparing the current queue against the main queue is not a valid way to check whether you are running on the main thread.

Use [NSThread isMainThread] or pthread_main_np() to explicitly check whether you are on the main thread if that is what you want to know.

You can be on the main thread without the current queue being the main queue, and you can be on the main queue without the current thread being the main thread (the latter only if dispatch_main() has been called, but still).

In recent releases this is documented explicitly in the CAVEATS section of the dispatch_get_main_queue(3) manpage:

The result of dispatch_get_main_queue() may or may not equal the result of dispatch_get_current_queue() when called on the main thread. Comparing the two is not a valid way to test whether code is executing on the main thread. Foundation/AppKit programs should use [NSThread isMainThread]. POSIX programs may use pthread_main_np(3).

In general you should avoid using queue pointer comparison to influence program logic. Dispatch queues exist in a dependency tree (the target queue hierarchy) and comparing individual leaves in that tree without taking their interdependency into account does not provide sufficient information to make safe decisions.

If you really need program logic based on queue interdependency, use the dispatch_get_specific(3)/dispatch_queue_set_specific(3) APIs which are target-queue aware and much more explicit.



来源:https://stackoverflow.com/questions/17489098/is-this-the-right-way-to-compare-two-gcd-queues

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