Tejaswi Burgula
Tejaswi Burgula

Reputation: 349

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?

Upvotes: 6

Views: 1524

Answers (2)

Nicola Bizzoca
Nicola Bizzoca

Reputation: 1145

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

Upvotes: 3

AaronI
AaronI

Reputation: 862

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.

Upvotes: 3

Related Questions