1

If I have a three-element array and multiple threads attempting to access those values. Is there a race condition if I protect each of the three indexes with a separate lock?

In other words, if I know that no two threads will access the same index at the same time, but that multiple threads may access different indexes at the same time, is that enough to avoid the race condition?, or should I ensure that no two threads access the entire array at the same time, even if they access different indexes?

  • Designing systems where the threads don't ever overlap in the data they use is the key objective behind "lock-free concurrency." What you've described should be fine, as long as nobody is adding/removing elements to the array. – Alexander Sep 24 '22 at 10:55
  • If you are going to perform read/write operations from multiple threads consider to use an `actor` rather than dated `NSLock`. – vadian Sep 24 '22 at 11:05
  • 1
    If the array contains value types, even if you know no two threads ever access the same index, there is the potential for data races because Swift arrays are copy-on-write, so when you modify it, you're potentially modifying more than just that element. If it contains reference types, changing the what instances are in the array would have the same potential; however, changing values in those instances would not (assuming those instances are only accessible through the array). – Chip Jarred Sep 24 '22 at 11:38
  • If you want to live on the edge (and the debugging that goes with it), you could potentially do it with pointers. There is a trick to allow `UnsafeMutablePointer`s to escape `Array`'s `withUnsafeMutableBuffer` method, despite Swift's mechanism to invalidate them on its return. There be dragons there, so I'm not recommending it. Just saying it's possible. – Chip Jarred Sep 24 '22 at 11:42

0 Answers0