我正在尝试编写一些线程安全的方法,所以我使用:
...
dispatch_queue_t main = dispatch_get_main_queue();
dispatch_sync(main,^{
[self doSomethingInTheForeground];
});
...
但是,如果我在主线程上,则没有必要,并且我可以跳过所有这些调度调用,所以我想知道我当前在哪个线程上。我怎么知道这个?
或者,也许这样做并没有什么区别(在性能上)?
做这个比较可以吗?
if (dispatch_get_main_queue() == dispatch_get_current_queue()){...}
更新答案:
Apple 文档已更改,现在说“当从提交块的上下文之外调用时,如果从主线程执行调用,则此函数返回主队列。如果从任何其他线程进行调用,则此函数返回默认并发队列。”所以检查dispatch_get_main_queue() == dispatch_get_current_queue()
应该管用。
原答案:
Using dispatch_get_main_queue() == dispatch_get_current_queue()
行不通的。的文档dispatch_get_current_queue
说“当在提交块的上下文之外调用时,此函数返回默认并发队列”。默认并发队列不是主队列。
[NSThread isMainThread]
应该为你想要的工作。注意[NSThread isMainThread]
但对于主队列以外的队列来说可能是正确的,例如,当调用dispatch_sync
从主线程。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)