2023-02-21

Writing to different Swift array indexes from different threads

I see frequent mention that Swift arrays, due to copy-on-write, are not threadsafe, but have found this works, as it updates different and unique elements in an array from different threads simultaneously:

//pixels is [(UInt8, UInt8, UInt8)]

let q = DispatchQueue(label: "processImage", attributes: .concurrent)
q.sync {

  DispatchQueue.concurrentPerform(iterations: n) { i in
     ... do work ...
     pixels[i] = ... store result ...
  }
}

(simplified version of this function)

If threads never write to the same indexes, does copy-on-write still interfere with this? I'm wondering if this is safe since the array itself is not changing length or memory usage. But it does seem that copy-on-write would prevent the array from staying consistent in such a scenario.

If this is not safe, and since doing parallel computations on images (pixel arrays) or other data stores is a common requirement in parallel computation, what is the best idiom for this? Is it better that each thread have its own array and then they are combined after all threads complete? It seems like additional overhead and the memory juggling from creating and destroying all these arrays doesn't feel right.



No comments:

Post a Comment