简体   繁体   English

pthread_key_t和方法pthread_key_create如何工作?

[英]How does pthread_key_t and the method pthread_key_create work?

I am having some trouble figuring out how pthread_key_t and pthread_key_create work. 我在弄清楚pthread_key_t和pthread_key_create如何工作时遇到了一些麻烦。 From my understand, each thread has TLS (thread local storage) and that a key is used to access the thread local storage. 据我所知,每个线程都有TLS(线程本地存储),并且一个密钥用于访问线程本地存储。 What I do not get is when a key is created, does every thread get to use it? 我没有得到的是当创建一个密钥时,每个线程都可以使用它吗? Lets say Thread 0 creates key 0, can Thread 1 then use key 0? 让我们说线程0创建密钥0,线程1可以使用密钥0吗? If Thread 1 used key 0, would it access its own TLS or Thread 0's TLS? 如果线程1使用键0,它是否会访问自己的TLS或线程0的TLS?

Is there some global array or something that keeps track of all the keys being used? 是否有一些全局数组或某些东西可以跟踪所使用的所有密钥?

pthread_keys are just what you said, thread local storage referred to by a common key. pthread_keys就是你所说的,通过公共密钥引用的线程本地存储。 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). 一个简单的例子(也是设计的),假设您正在构建一个异步服务器(如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. 因此,当一个请求进入时,新的线程被旋转,并且线程在Client_Connection-> WhatAmIDoing键中存储指向“请求”结构的指针。 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. 线程现在不必传递该指针,因为线程执行的任何函数都可以简单地调用pthread_getspecific()函数并获取指向它应该执行的操作的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM