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…
I came to this comment thread specifically to point this out, but you beat me to it. 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. # you might as well imagine this happening original = x[i] new_val = original…
lock (_gate) {
x[i] --;
}
At least in C# it is considered preferable to lock on a private field, as opposed to locking on `this`, so nobody else also locks on your instance, potentially causing a deadlock.I suppose this applies to `@synchronized` in Objective C as well.
I like that .NET Framework also provides some useful atomic methods, including this one:
Interlocked.Decrement (ref x[i]);
They come in handy.