How does pthread_key_t and the method pthread_key_create work?

前端 未结 1 718
野性不改
野性不改 2021-01-02 17:26

I am having some trouble figuring out how pthread_key_t and pthread_key_create work. From my understand, each thread has TLS (thread local storage) and that a key is used t

相关标签:
1条回答
  • 2021-01-02 18:23

    pthread_keys are just what you said, thread local storage referred to by a common key. So multiple threads use the same key, but get different storage space (per thread).

    A quick example (contrived too), say you were building an asynchronous server (like IMAP). You could keep track of client connections in an array, with each having a key for the current task/request. So when a request comes in a new thread is spun up and the thread stores in the Client_Connection->WhatAmIDoing key a pointer to the "request" structure. The thread now wouldn't have to pass around that pointer because any function that thread executes could simply call the pthread_getspecific() function and get the pointer to what it's supposed to be doing.

    0 讨论(0)
提交回复
热议问题