we use One-Time initialization for pthreads like this:
/* define a statically initialized pthread_once_t variable */
pthread_once_t once_var = PTHREAD_ONCE_INIT;
/* we call pthread_once function in threads */
int pthread_once(pthread_once_t *once_control, void (*init)(void));
when more than one thread is going to change the state of pthread_once_t variable, do we need a mutex for protecting it?
No, you don’t need a mutex for this. The
pthread_oncecall (link here) is guaranteed to be executed once and once only, even if multiple threads try it at the same time.It’s the
once_varthat’s protecting the call from being executed more than once. It will work as expected, provided that you:once_vartoPTHREAD_ONCE_INIT; andonce_varis not of automatic storage duration (eg, on the stack); andonce_varvariable.