Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_key_t and pthread_once_t?

Tags:

c++

unix

pthreads

Starting with pthreads, I cannot understand what is the business with pthread_key_t and pthread_once_t?

Would someone explain in simple terms with examples, if possible?

thanks

like image 202
vehomzzz Avatar asked Nov 28 '22 19:11

vehomzzz


1 Answers

pthread_key_t is for creating thread thread-local storage: each thread gets its own copy of a data variable, instead of all threads sharing a global (or function-static, class-static) variable. The TLS is indexed by a key. See pthread_getspecific et al for more details.

pthread_once_t is a control for executing a function only once with pthread_once. Suppose you have to call an initialization routine, but you must only call that routine once. Furthermore, the point at which you must call it is after you've already started up multiple threads. One way to do this would be to use pthread_once(), which guarantees that your routine will only be called once, no matter how many threads try to call it at once, so long as you use the same control variable in each call. It's often easier to use pthread_once() than it is to use other alternatives.

like image 177
Adam Rosenfield Avatar answered Nov 30 '22 09:11

Adam Rosenfield