Skip to content
aleclarson edited this page Oct 22, 2014 · 7 revisions

Queues manage the execution of closures you give to them.

Serial queues execute their closures one at a time.

Concurrent queues execute their closures many at a time (depending on system conditions).

All queues always execute their closures in order. Serial queues' closures always finish in order. Concurrent queues' closures do not always finish in order.

myQueue.isConcurrent is useful for knowing what kind of queue you're working with.

Queue runs on top of the traditional dispatch queue.


Adding closures to a Queue

Call sync() if you want to wait for the closure you passed to finish before continuing on.

gcd.sync {
  println("This will always be called first.")
}
println("This will always be called second.")

Call async() if you don't want to wait for the closure you passed to finish before continuing on.

gcd.async {
  println("This might be called first.")
}
println("This might be called first, too.")

Which Queue am I currently in?

gcd.main.async {
  let currentQueue: Queue = gcd.current // gcd.main
  let queueIsCurrent: Bool = currentQueue.isCurrent // true
}

current is only available on gcd.

isCurrent is available on all Queues.


Queue automatically prevents deadlocks!

The example below would deadlock the main queue if you weren't using this framework...

func doSomething () {
  gcd.main.sync {
    // Doing UI stuff, so ensure the current queue is the main queue!
  }
}

gcd.main.sync {
  doSomething() // Normally a deadlock because you called `sync()` inside a `sync()` of the same queue.
}

Instead, the Queue just pretends that you never called sync() inside doSomething(), so your code is safe from deadlocking the current queue! 😉

Clone this wiki locally