4 ms·
If I implement the mutex as you suggest -- by using the native semaphore directly, with no separate counter -- the running time of "testBenaphore" increases fro
by preshing 12y ago
If I implement the mutex as you suggest -- by using the native semaphore directly, with no separate counter -- the running time of "testBenaphore" increases from 375 ms to 3 seconds on my Windows PC.
As mentioned in the article, most mutex implementations already use this trick. So you can just use std::mutex, and things are fine.
In the past, though, runtime environments weren't so well-developed, so there definitely [was a point](http://www.haiku-os.org/legacy-docs/benewsletter/Issue1-26.html#Engineering1-26 http://www.haiku-os.org/legacy-docs/benewsletter/Issue1-26.h...).
- kazinator 12y agoThat looks like some API/kernel call overhead; you've moved the fast path of the semaphore implementation into user space. But what you have there is undeniably a semaphore implementation: atomically tweak a counter, and based on that result, wait or signal.
- preshing 12y ago> you've moved the fast path of the semaphore implementation into user space. I see now why your original comment was a bit inflammatory. I should have been more clear in the post that by "lightweight", I meant exactly that: "fast path in user space". I guess not everyone shares this vocabulary. I'll improve the post. You're right that this lightweight mutex is a semaphore, of course. But not every semaphore is a lightweight mutex. So the technique isn't pointless.
- asveikau 12y agoSeems like that's what any sane modern user space sync primitives would do: do the atomic ops in user space for the fast path, enter the kernel when it's time to block. Like the "futex" in Linux. I suppose it is a fair point that the thing you use to enter the kernel doesn't have to be itself a semaphore.
- TwoBit 12y agoLong ago when developing for the PS2 gaming machine, we used this exact technique to achieve a 10x faster mutex on that platform than using the semaphore directly as a mutex, so it hasn't always been pointless.