iOS Concurrency with GCD & Operations

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

Part 2: Concurrency Problems & Solutions

14. Challenge: Make Number Class Thread-Safe

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: 13. Make Class Thread-safe Next episode: 15. Operations

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.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Challenge: Make Number Class Thread-safe

In the previous exercise, you used a private concurrent queue and dispatch barrier to create a thread-safe version of the Person class. In this challenge, you’ll create a thread-safe version of a Number class. Open the NumberChanger project in the starter folder. Build and run it to see its output is jumbled, like the Person names were. Turn on TSan to confirm the race condition.

let isolationQueue = DispatchQueue(
  label: "com.kodeco.number.isolation",
  attributes: .concurrent)
isolationQueue.async(flags: .barrier) {
  randomDelay(0.1)
  self.value = value
  randomDelay(0.5)
  self.name = name
}
isolationQueue.sync {
  "\(self.value) :: \(self.name)"
}
Current number: 2 :: two
Current number: 2 :: two
Current number: 3 :: three
Current number: 4 :: four
Current number: 5 :: five
Current number: 6 :: six
Final number: 6 :: six