只是个队列,不是一个线程。
Getting the Global Concurrent Dispatch Queues
The system provides each application with three concurrent dispatch queues. These queues are global to the application and are differentiated only by their priority level. Because they are global, you do not create them explicitly. Instead, you ask for one of the queues using the dispatch_get_global_queue
function, as shown in the following example:
dispatch_queue_t aQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); |
Creating Serial Dispatch Queues
Unlike concurrent queues, which are created for you, you must explicitly create and manage any serial queues you want to use. You can create any number of serial queues for your application but should avoid creating large numbers of serial queues solely as a means to execute as many tasks simultaneously as you can. If you want to execute large numbers of tasks concurrently, submit them to one of the global concurrent queues. When creating serial queues, try to identify a purpose for each queue, such as protecting a resource or synchronizing some key behavior of your application.
Listing 3-2 shows the steps required to create a custom serial queue. The dispatch_queue_create
function takes two parameters: the queue name and a set of queue attributes. The debugger and performance tools display the queue name to help you track how your tasks are being executed. The queue attributes are reserved for future use and should be NULL
.
Listing 3-2 Creating a new serial queue
dispatch_queue_t queue; |
queue = dispatch_queue_create("com.example.MyQueue", NULL); |
Getting Common Queues at Runtime
Grand Central Dispatch provides functions to let you access several common dispatch queues from your application:
-
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. -
Use the
dispatch_get_main_queue
function to get the serial dispatch queue associated with your application’s main thread. This queue is created automatically for Cocoa applications and for applications that either call thedispatch_main
function or configure a run loop (using either theCFRunLoopRef
type or anNSRunLoop
object) on the main thread. -
Use the
dispatch_get_global_queue
function to get any of the shared concurrent queues.
Adding a Single Task to a Queue
There are two ways to add a task to a queue: asynchronously or synchronously. When possible, asynchronous execution using the dispatch_async
and dispatch_async_f
functions is preferred over the synchronous alternative.
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- // 耗时的操作
- // 从当前线程异步到主线程queue中执行
- dispatch_async(dispatch_get_main_queue(), ^{
- // 更新界面
- });
- });