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.

Transcript: 14. Challenge: Make Number Class Thread-Safe

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.

Your challenge is to use a private concurrent queue and dispatch barrier to create a thread-safe Number class. You don’t have to subclass the non-thread-safe Number, just comment it out. Pause this video while you complete this challenge, then resume playing the video to see my solution.

In Number.swift, duplicate the Number class, then comment out one of the copies. And add an isolationQueue:

let isolationQueue = DispatchQueue(
  label: "com.kodeco.number.isolation",
  attributes: .concurrent)

Next, dispatch everything in changeNumber to isolationQueue, with the .barrier flag:

isolationQueue.async(flags: .barrier) {
  randomDelay(0.1)
  self.value = value
  randomDelay(0.5)
  self.name = name
}

Finally, for the computed var number, return the same value as a synchronous dispatch to isolationQueue :

isolationQueue.sync {
  "\(self.value) :: \(self.name)"
}

Build and run again. This time, TSan doesn’t find any race condition, and your output is correct:

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

As with Person names, the synchronous read of numbers might not print all of them.

Turn off TSan, just to get into the habit of turning it off when you no longer need it.