4 ms·
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. T
by SeoxyS 14y ago
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 - 1
x[i] = new_val
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:
@synchronized(self) {
int original = x[i];
int new_val = original - 1;
x[i] = new_val;
}
- danabramov 14y agoIf 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.