Friday, 15 February 2019

Thread-Safe Array

Swift playground: https://github.com/Sylvia-YiyinShen/ThreadSafeArrayExample


Array in Swift is not thread-safe same as Dictionary type, since its mutating is based on copy-to-write mechanism.

Run the example code below to stimulate a race condition, you probably will see the 47 or other number is missing.



The root cause can be: when the two concurrent thread trying to add 47 48, we got a copy of the current array [0...46] for both of them,
 [0...46] becomes [0...46,47] and overwrite the original array
 [0...46] becomes [0...46,48], but it happens later after the other thread and overwrite array as [0...46,48].
 We will lose 47 as a result.

 Therefore, the array need to be synchronize/locked to make sure only one thread can mutate it at the same time.





Synchronization via Atomic class wrapping a value




No comments:

Post a Comment