iOS Concurrency with GCD & Operations

Sep 12 2023 · Swift 5.8, macOS 13, iOS 16, Xcode 14.3

Part 2: Concurrency Problems & Solutions

12. Explore Priority Inversion

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 11. Concurrency Problems Next episode: 13. Make Class Thread-safe

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 12. Explore Priority Inversion

Prioritize Work with Quality of Service Classes

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

In this exercise, you’ll use a semaphore and queues with different quality of service values to create a priority inversion: A low priority queue gets a lock on a resource, so a high priority queue has to wait until the resource is free. In the starter playground, create global queues with higher and lower qos values than the medium queue, and a semaphore with value 1:

let high = DispatchQueue.global(qos: .userInteractive) 
let medium = DispatchQueue.global(qos: .userInitiated) // existing
let low = DispatchQueue.global(qos: .background)
let semaphore = DispatchSemaphore(value: 1)
high.async {
  semaphore.wait()
  defer { semaphore.signal() }
  print("High priority task is now running")
  sleep(1)
  PlaygroundPage.current.finishExecution()
}
low.async {
  semaphore.wait()
  defer { semaphore.signal() }
  print("Low priority task is now running")
}
high.async {
  sleep(2)
  print("High priority task is now waiting")
  semaphore.wait()  // existing
  defer { semaphore.signal() }  // existing
  
  print("High priority task is now running")  // existing
  PlaygroundPage.current.finishExecution()  // existing
}
low.async {
  semaphore.wait()  // existing
  defer { semaphore.signal() }  // existing
  
  print("Low priority task is now running")  // existing
  sleep(5)
}
for i in 1 ... 10 {
  medium.async {
    print("Running medium task \(i)")
    let waitTime = Double(Int.random(in: 0..<7))
    Thread.sleep(forTimeInterval: waitTime)
  }
}
Running medium task 2
Running medium task 1
Running medium task 3
Running medium task 4
Running medium task 5
Running medium task 6
Running medium task 7
Running medium task 9
Running medium task 8
Low priority task is now running
Running medium task 10
High priority task is now waiting
High priority task is now running