Leave a rating/review
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.