Junior — Middle
Do the data structures used ensure safe operation in parallel streams?
sobes.tech AI
Answer from AI
In iOS, standard data structures such as arrays (Array), dictionaries (Dictionary), and sets (Set) are not thread-safe. This means that concurrent access from multiple threads without synchronization can lead to data races and unpredictable behavior.
To ensure safety during parallel operations, the following are used:
DispatchQueuequeues with proper synchronization policies (e.g., serial queue for writing).- Classes from
NSLock,NSRecursiveLock, and other locking mechanisms. - High-level constructs such as
DispatchSemaphoreorOperationQueue.
Example of using a serial queue to protect access to an array:
let queue = DispatchQueue(label: "com.example.arrayQueue")
var array: [Int] = []
func appendElement(_ element: Int) {
queue.sync {
array.append(element)
}
}
Thus, safety is achieved not by the data structures themselves but through external synchronization.