dispatch_get_global_queue和dispatch_queue_create有什么区别? [英] What is the difference between dispatch_get_global_queue and dispatch_queue_create?

查看:2217
本文介绍了dispatch_get_global_queue和dispatch_queue_create有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个中等复杂的iOS程序,需要为一些较长的操作(解析,连接到网络等)提供多个线程。但是,我对 dispatch_get_global_queue dispatch_queue_create 之间的区别感到困惑。

I'm writing a moderately complex iOS program that needs to have multiple threads for some of its longer operations (parsing, connections to the network...etc). However, I'm confused as to what the difference is between dispatch_get_global_queue and dispatch_queue_create.

我应该使用哪一个,你能否简单解释一下这有什么区别?谢谢。

Which one should I use and could you give me a simple explanation of what the difference is in general? Thanks.

推荐答案

作为文档描述,全局队列适用于并发任务(即你将异步调度各种任务,如果它们同时运行你会非常高兴)并且如果你不想遇到创建和销毁自己队列的理论开销。

As the documentation describes, a global queue is good for concurrent tasks (i.e. you're going to dispatch various tasks asynchronously and you're perfectly happy if they run concurrently) and if you don't want to encounter the theoretical overhead of creating and destroying your own queue.

如果需要一个串行队列(即需要一次执行一个调度块),创建自己的队列非常有用。这在许多场景中都很有用,例如当每个任务依赖于前一个任务或协调与来自多个线程的某些共享资源的交互时。

The creating of your own queue is very useful if you need a serial queue (i.e. you need the dispatched blocks to be executed one at a time). This can be useful in many scenarios, such as when each task is dependent upon the preceding one or when coordinating interaction with some shared resource from multiple threads.

不太常见,但是如果您需要使用障碍与并发队列一起使用。在该场景中,使用 DISPATCH_QUEUE_CONCURRENT 选项创建并发队列(即 dispatch_queue_create )并将障碍与此结合使用队列。你永远不应该在全局队列上使用障碍。

Less common, but you will also want to create your own queue if you need to use barriers in conjunction with a concurrent queue. In that scenario, create a concurrent queue (i.e. dispatch_queue_create with the DISPATCH_QUEUE_CONCURRENT option) and use the barriers in conjunction with that queue. You should never use barriers on global queues.

我的总法律顾问是你需要一个串行队列(或者需要使用障碍),然后创建一个队列。如果不这样做,请继续使用全局队列并绕过创建自己的开销。

My general counsel is if you need a serial queue (or need to use barriers), then create a queue. If you don't, go ahead and use the global queue and bypass the overhead of creating your own.

如果你想要一个并发队列,但想要控制可以并发运行的操作数量,您还可以考虑使用 NSOperationQueue ,其中包含 maxConcurrentOperationCount 属性。这在执行网络操作时很有用,并且您不希望将太多并发请求提交到您的服务器。

If you want a concurrent queue, but want to control how many operations can run concurrently, you can also consider using NSOperationQueue which has a maxConcurrentOperationCount property. This can be useful when doing network operations and you don't want too many concurrent requests being submitted to your server.

这篇关于dispatch_get_global_queue和dispatch_queue_create有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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