I've not understood the reason in use of pthread_key_create, can you tell why?

737 views Asked by At

We can pass argument to a thread when using pthread_create /(not key_), if it is over using value per thread. If about using static storage, we use mutexes, so, what is it saying we use pthread_key_create? With example & emphasize on why it is born (application & need of it)? I heard it is useful for migrating single threded applications, but they still use mutexes. So, what is the point?

Thanks!

1

There are 1 answers

1
Steve Jessop On

pthread_key_create is used to create a unique identifier for a piece of thread-local storage.

Each thread can then store a different value for each key. This can be useful when migrating code that initially uses globals, but where you want each thread of execution to have its own independent version of the global value. You can use thread-local storage in place of the global.

You don't need to use mutexes when accessing thread-local data belonging to the thread you're in.