From the course: Practical Design Patterns in Swift

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Making the singleton thread-safe

Making the singleton thread-safe - Swift Tutorial

From the course: Practical Design Patterns in Swift

Start my 1-month free trial

Making the singleton thread-safe

- [Instructor] Let's make our singleton thread safe. You can open the project from the exercize files folder chapter two two four begin. Concurrent data reads won't cause any issues, however, pedal updates or concurrent write and read operations will cause data corruption and crashes. So, our goal is to prevent concurrent execution of the set value forKey method. Also, we shouldn't execute set value forKey and any of the data retrieval methods at once. We can achieve that easily with the help of a serialQueue. SerialQueues guarantee that tasks get executed one at a time. Let's start by creating the serialQueue. I'm going to stop this task now and let's scroll up. I'll make the Queue private. Private let serialQueue equals DispatchQueue and let's provide the label. This initializer will create a serialQueue. Now, I'm going to serialize the access to the set value forKey first. Let's scroll down and instead of accessing the dictionary directly I place this call into a serialQueue sync…

Contents