AIWasabi

In modern software programming, concurrency and thread-safety are very crucial topics.

Let’s look at an example how to create thread-safe array in Swift by using GCD ( Grand Central Dispatch). In the code below, we are using a concurrent queue to allow all the readings in parallel. And with the barrier flag for writings, it ensures that the concurrent queue does not execute any other tasks while executing the barrier process. Once the barrier process is complete, then the readings behind it can run in parallel again.

class ThreadSafeArray<T> {    var array = [T]()
let concurrentQueue = DispatchQueue(label: "queue.label", attributes: .concurrent)
// reading array
var first: T? {
var result: T?
self.concurrentQueue.sync {
result = self.array.last
}
return result
}
// updating array
func append(_ newElement: T) {
self.concurrentQueue.async(flags: .barrier) {
self.array.append(newElement)
}
}
}

--

--