Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How pthread_once() is implemented internally?

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?

like image 711
Tejaswi Burgula Avatar asked Jan 21 '16 16:01

Tejaswi Burgula


2 Answers

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.

like image 134
AaronI Avatar answered Dec 10 '22 05:12

AaronI


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

like image 26
Nicola Bizzoca Avatar answered Dec 10 '22 04:12

Nicola Bizzoca