1

I am working on a project that collects (1000+) data points from a database and updates itself every few seconds. To keep my main thread from locking, I have to read, sort, and save data in a background thread. I would like to understand the difference between two background calls.

In this article the author gives us a good example of using a background thread like so: DispatchQueue(label: "foo", qos: .utility).async {}

In another example on this site, I found a great example of an extension of DispatchQueue. This one does not use a label.

I know these two methods are different but how exactly (other than one being an extension)? Second question: is it best practice to wait for a background thread activity to finish its job before calling it again? Or does that matter?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
temp_
  • 1,238
  • 2
  • 12
  • 24
  • 3
    FYI - your question is not about "Swift" threading. It's about Grand Central Dispatch. The language doesn't matter. – rmaddy Nov 26 '18 at 22:02

2 Answers2

2

The only surface difference between the behavior of a dispatch queue that you make yourself (the first example) and a built-in global dispatch queue (the second example) is that the former is serial (by default) while the latter is concurrent.

Second question: is it best practice to wait

It is never right to "wait". If you have multiple tasks to coordinate you can use GCD to do that (e.g. dispatch groups).

matt
  • 515,959
  • 87
  • 875
  • 1,141
2

I agree 100% with everything that matt said (+1).

A couple of additional observations:

  1. As he said, the key difference is that global queues are concurrent queues, whereas when you create a queue, it defaults to being a serial queue. E.g. this is a serial queue:

    let queue = DispatchQueue(label: "foo", qos: .utility)
    

    You can, of course, create your own concurrent queue:

    let queue = DispatchQueue(label: "foo", qos: .utility, attributes: .concurrent)
    
  2. Let's assume for a second that you decided that you really did want to use a concurrent queue. That then begs the question why you'd create your own named custom concurrent queue vs using one of the global queues. There are a few reasons:

    • You can see your custom queue names when debugging in Xcode and Instruments. E.g. here is a breakpoint where I can see which queue my breakpoint is on (as well as what other threads are being used by that queue, too):

      enter image description here

    • Certain more advanced techniques, such as barriers, can not be performed on global queues. For those narrow set of applications, you might want to use your own custom concurrent queue.

Rob
  • 415,655
  • 72
  • 787
  • 1,044