Is the pthread_once_t mutex variable required?

we use one-time initialization for pthreads as follows:

/* 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 changes the state of a variable pthread_once_t, do we need a mutex to protect it?

+3
source share
3 answers

No, you don’t need a mutex for this. A call pthread_once( here ) is guaranteed to be executed once and only once, even if several threads try it at the same time.

This once_var, which protects the call from being executed more than once. It will work as expected, provided that you:

  • enter once_varin PTHREAD_ONCE_INIT; and
  • , once_var (, );
  • once_var.
+8

pthread_once . pthread_once_t .

+5

If this happened, this whole mechanism would be completely useless. No matter what you use to ensure that you only initialize this mutex, as soon as you could just as easily do what you use, you use this mechanism to do it once.

+2
source

All Articles