Re:Ruby core classes aren't thread safe
by danabramov on Monday February 25, 2013 @05:17PM
(#5282251)
If I understand correctly, this corresponds to `lock` in C#:
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.
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: