|
|
|
|
|
by tomp
5031 days ago
|
|
It's not that Arrays are not thread safe; it's just that the code was written in a non-thread-safe way. Writing x[i] -= 1
actually means x[i] = x[i] - 1
So, there's a read, a subtraction, and a write, and they all happen sequentially. Since they are not in a transaction or protected by a mutex, nothing guarantees that other thread don't mutate `x[i]` in the mean time.This has nothing to do with Ruby, and nothing to do with multicore, either. Even on a single CPU core, threads might interleave and cause unexpected behavior. |
|
It has nothing to do thread safety, and everything to do with atomicity. This is not a single atomic operation, but rather three atomic (and thread-safe) operations which are bound together with the assumption that the entire thing is atomic when it is not.
Which is why you need to use a mutex to make the entire operation atomic, at a small performance cost.The Objective-C compiler actually adds a nice bit of syntax for this, you can simply wrap your code in @synchronized: