Hacker News new | ask | show | jobs
by acqq 2363 days ago
So this it acquires fully in userspace if there's no contention, it even spins if there is contention, and then if that wasn't enough it lets the thread sleep with the timeout.

Which matches the description of that library:

https://github.com/Amanieu/parking_lot

"This library provides implementations of Mutex, RwLock, Condvar and Once that are smaller, faster and more flexible than those in the Rust standard library"

"Uncontended lock acquisition and release is done through fast inline paths which only require a single atomic operation.

Microcontention (a contended lock with a short critical section) is efficiently handled by spinning a few times while trying to acquire a lock.

The locks are adaptive and will suspend a thread after a few failed spin attempts."

The only thing that I'm missing is how often the sleeping threads wake, as a bad constant can increase the CPU use.

3 comments

Does it really sleep for a specified period instead of doing directed wake-ups? If so that's very far from ideal...
No, a thread that fails to acquire the mutex sleeps until the thread that is releasing the mutex explicitly wakes it. On Linux this is achieved via FUTEX_WAIT / FUTEX_WAKE.
Ah, thanks for the info.

I would imagine the unlocking call would wake up the sleeping thread so it won't keep waking up periodically.

The user-mode only implementation sounds interesting. The only downside is it won't work with inter-process locking.

How does it know that said critical section is short? Guessing?

Likely a hard linear-quadratic expanding threshold. They tend to waste a lot of CPU power in specific algorithms.

There are better, more intrusive ways of solving this problem on language level.

It doesn't attempt to determine the size of the critical section, AFAIK. I think it's saying that sleeping immediately when failing to acquire the lock would significantly hurt small critical sections, and so instead they spin a few times to avoid punishing those scenarios.