Swift Thread-Safe Arrays
Be careful! This applies to value types!
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 11.7, and Swift 5.2.4
- You will be expected to make a Single View SwiftUI Application in Swift.
Array: An ordered series of objects which are the same type
Concurrency: means that two tasks can start, run and complete in overlapping time periods
Parallelism: is about performing work at the same time
Concurrency is a big part of programming, and this article covers where you may actually encounter this in your day-to-day work as an iOS programmer.
Since many devices (including iOS devices) embrace the principles of parallelism (that is, executing on many threads at the same time).
There is a special type of problem in Computer Science — The Readers-Writers problem.
Because there are multiple threads, one thread may be reading a shared resource (in this case an Array) while another thread writes the same resource.
Here lies disaster!
Since Arrays are Value types but this doesn’t help in preventing the Readers-Writers problem.
Warning: The following code is not thread-safe (by definition — that is the point). This means that the code can and will crash at times because the code is simultaneously reading and writing at the same location — this is the point.
We set up an array (I’ve called it
Array due to creativity issues).
Actual output: A crash, or all sorts of variations where we have corrupted data and:
- the output does, or does not have 6 elements
This is trash! We must fix this!
Note: The contents of the actual array can still be messed up bad, but this is not particuarly relevant to this example.
We place Swift’s Dispatch Barrier to allow concurrent reads while blocking write.
This particular solution is not generic, as this is not a prerequisite of this article!
Note: The contents of the actual array can still be messed up bad, but this is not particularly relevant to this example.
You need to be careful even with value types when in a multi-threaded environment. This article has given a rather brief introduction and I hope you’ve enjoyed it.
If you’ve any questions, comments or suggestions please hit me up on Twitter