什么GCD队列,主要与否,我正在运行? [英] What GCD queue, main or not, am I running on?

查看:146
本文介绍了什么GCD队列,主要与否,我正在运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一些线程安全的方法,所以我使用:

I am trying to write some thread safe methods so I am using:

...
dispatch_queue_t main = dispatch_get_main_queue();
dispatch_sync(main,^{
  [self doSomethingInTheForeground];
});
...

但是如果我在主线程没有必要,我可以跳过所有这些调度调用,所以我想知道我目前的线程。我如何知道这一点?

But If I am on the main thread that is not necessary, and I can skip all those dispatch calls, so I would like to know what thread I currently am on. How can I know this?

或者,也许它没有区别(在性能上)做吗?

Or, perhaps it does not make difference (in performance) doing it?

是否可以进行此比较?

if (dispatch_get_main_queue() == dispatch_get_current_queue()){...}


推荐答案

p> 更新的答案

Apple文档已更改,现在说当从提交的块的上下文外调用时,此函数如果从主线程执行调用,则返回主队列;如果从任何其他线程调用,则此函数返回默认并发队列。所以检查 dispatch_get_main_queue()== dispatch_get_current_queue()应该工作。

The Apple docs have changed and now say "When called from outside of the context of a submitted block, this function returns the main queue if the call is executed from the main thread. If the call is made from any other thread, this function returns the default concurrent queue." so checking dispatch_get_main_queue() == dispatch_get_current_queue() should work.

原始答案

使用 dispatch_get_main_queue == dispatch_get_current_queue()将无法工作。 dispatch_get_current_queue 的文档说当在提交的块的上下文之外调用时,此函数返回默认并发队列。默认并发队列不是主队列。

Using dispatch_get_main_queue() == dispatch_get_current_queue() won't work. The docs for dispatch_get_current_queue say "When called outside of the context of a submitted block, this function returns the default concurrent queue". The default concurrent queue is not the main queue.

[NSThread isMainThread] 应该为您想要的工作。注意 [NSThread isMainThread] 对于非主队列的队列可以是真的,例如,当调用 dispatch_sync 从主线程。

[NSThread isMainThread] should work for what you want. Note that [NSThread isMainThread] can be true for for queues other than the main queue though, e.g., when calling dispatch_sync from the main thread.

这篇关于什么GCD队列,主要与否,我正在运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆