Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In GCD, when do I use a global concurrent queue vs a custom concurrent queue?

In GCD, there are two ways I can run blocks concurrently.

I can use one of the global pools:

DispatchQueue.global().async() {
  // do work
}

or I can create my own queue:

let queue = DispatchQueue(label: "process images", attributes: [.concurrent])
queue.async {
  // do work
}

but I can't find much information on when to prefer one over the other.

Some places (including this summary of mailing list posts from the libdispatch maintainer) suggest that you really shouldn't use the global queues.

Yet most code examples just dispatch to a global queue, and there are even some sources that say you really shouldn't use custom queues - and should prefer the global queues.

Which situations are better for each kind of queue? Somewhat relatedly, some articles advise preferring serial queues over concurrent queues - but obviously they have completely different parallelism characteristics, so it's odd to see them suggested as interchangeable.

like image 958
Bill Avatar asked Aug 08 '18 19:08

Bill


People also ask

Is global queue serial or concurrent?

Concurrent queues (also known as a type of global dispatch queue) execute one or more tasks concurrently, but tasks are still started in the order in which they were added to the queue. The currently executing tasks run on distinct threads that are managed by the dispatch queue.

What is global queue in IOS?

A dispatch queue that is bound to the app's main thread and executes tasks serially on that thread. typealias dispatch_queue_global_t. A dispatch queue that executes tasks concurrently using threads from the global thread pool.

What is difference between serial and concurrent queue?

Since its concurrent queue, tasks may not finish in the order they are added to queue. But with synchronous operation it does although they may be processed by different threads. So, it behaves as this is the serial queue. Remember using GCD you are only adding task to the Queue and performing task from that queue.

Is Dispatchqueue main concurrent?

In general, dispatch queues will only perform one task at a time in a first-in, first-out kind of fashion. They can, however, be configured to schedule work concurrently. The main dispatch queue is a queue that runs one task at a time.


1 Answers

In addition to concerns about efficiency and thread explosion, with your own concurrent queue, you can:

  • Specify a label that's meaningful to you for debugging
  • Suspend it
  • Set and get app-specific data
  • Submit barrier tasks

None of these are possible with the global concurrent queues.

like image 147
Ken Thomases Avatar answered Oct 17 '22 14:10

Ken Thomases