Skip to content

Instantly share code, notes, and snippets.

@jeksys
Last active June 30, 2025 08:46
Show Gist options
  • Select an option

  • Save jeksys/8dec2273e61ca18dd5b468960f504570 to your computer and use it in GitHub Desktop.

Select an option

Save jeksys/8dec2273e61ca18dd5b468960f504570 to your computer and use it in GitHub Desktop.
Thread-Safe Arrays in Swift

What's concurrency

Concurrency means running more than one task at the same time.

What is a race condition?

When you have two threads changing a variable simultaneously. It’s possible to get unexpected results. Imagine a bank account where one thread is subtracting a value to the total and the other is adding a value.

What's thread safe in Swift

Nothing in Swift is intrinsically threadsafe Except: reference and static vars

Serial Queue Method

let queue = DispatchQueue(label: "MyArrayQueue")
queue.async() {
  // Manipulate the array here
}
queue.sync() {
  // Read array here
}

Concurrent Queue Method shared exclusion lock via barrier

let queue = DispatchQueue(label: "MyArrayQueue", attributes: .concurrent)
queue.async(flags: .barrier) {
  // Mutate array here
}
queue.sync() {
  // Read array here
}

Race condition test

var array = [Int]()
DispatchQueue.concurrentPerform(iterations: 1000) { index in
    let last = array.last ?? 0
    array.append(last + 1)
}

Swift uses a copy-to-write technique for value types as soon as it starts mutating it.

https://medium.com/@mohit.bhalla/thread-safety-in-ios-swift-7b75df1d2ba6

https://medium.com/swiftcairo/avoiding-race-conditions-in-swift-9ccef0ec0b26

https://gist.github.com/basememara/afaae5310a6a6b97bdcdbe4c2fdcd0c6

https://basememara.com/creating-thread-safe-arrays-in-swift/

https://xidazheng.com/2016/10/03/race-conditions-threads-processes-tasks-queues-in-ios/

@RomanPodymov
Copy link

RomanPodymov commented Jun 30, 2025

Hello @jeksys
Just want to mention that now this can be done easily with actor:

actor ThreadSafeArray<T> {
    private var rawData: [T] = []

    var data: [T] {
        rawData
    }

    func set(data: [T]) {
        rawData = data
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment