Do we use any locking mechanism inside pthread_once()? What is the cost of using pthread_once() instead of using pthread_mutex_lock() and pthread_mutex_unlock() in the threadsafe singleton class?
The spec does not define how pthread_once
and pthread_mutex_lock
must be implemented, but only how they must behave, so different platforms will have different implementations.
It is generally possible to make pthread_once
simpler than a mutex (since all it requires is an atomic test-and-set operation, and no blocking), but I would also suspect that pthread_mutex_lock
likely received more optimization because it is much more widely used.
If you care about performance, you will have to write a benchmark and run it on the platform you are targeting, and choose the one that's faster.
You can read directly the glibc implementation of pthread_once
You are lucky because recently glibc team unified all the different implementations across the the supported architectures. They were able to replace pure assembly with modern C code that also make use of C11 atomics support
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With