pthread_key_t和方法pthread_key_create如何工作? [英] How does pthread_key_t and the method pthread_key_create work?

查看:227
本文介绍了pthread_key_t和方法pthread_key_create如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在弄清楚pthread_key_t和pthread_key_create如何工作时遇到了一些麻烦.据我了解,每个线程都有TLS(线程本地存储),并且有一个密钥用于访问线程本地存储.我没有得到的是创建密钥时,每个线程都可以使用它吗?假设线程0创建了密钥0,线程1可以使用密钥0吗?如果线程1使用密钥0,它将访问自己的TLS还是线程0的TLS?

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 to access the thread local storage. 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? If Thread 1 used key 0, would it access its own TLS or Thread 0's TLS?

是否存在一些全局数组或某些可以跟踪所有正在使用的键的东西?

Is there some global array or something that keeps track of all the keys being used?

推荐答案

pthread_keys就是您所说的,是由公用密钥引用的线程本地存储.因此,多个线程使用相同的密钥,但获得不同的存储空间(每个线程).

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).

一个简单的例子(也有人为),说您正在构建一个异步服务器(如IMAP).您可以跟踪数组中的客户端连接,每个客户端连接都有一个用于当前任务/请求的密钥.因此,当一个请求进入时,一个新线程被启动,并且该线程在Client_Connection-> WhatAmIDoing键中存储一个指向请求"结构的指针.线程现在不必传递该指针,因为线程执行的任何函数都可以简单地调用pthread_getspecific()函数并获取指向其应做的事情的指针.

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.

这篇关于pthread_key_t和方法pthread_key_create如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆