How fast is Mutex on Linux?

I understand that Synchronization.Mutex is implemented using atomics and futex system calls on Linux. Have we run benchmarks comparing its performance to pthread_mutex_t from Glibc and Musl?

I have forked swift-nio and updated NIOLock et al. to use Synchronization.Mutex but haven’t submitted a pull request because I’m not yet sure if it’s faster than pthread_mutex_t. Also, I realize that Darwin platforms will need a different implementation due to availability requirements.

Thanks.

I can't give you specifics, but futexes on Linux should be faster than pthread_mutex_t. If you find that it's not the case (or rather, that futexes are measurably slow), that may be a bug in Swift's implementation and would be worth an issue.

On Darwin, Mutex is implemented in terms of os_unfair_lock which, on modern macOS, is slightly faster than a default-initialized pthread_mutex_t. Under the covers, a default-initialized pthread_mutex_t wraps the same kernel-level primitives as os_unfair_lock. A custom-configured pthread_mutex_t (such as a recursive one) will be slower.

3 Likes