c - 如何将 `pthread_t` 反向映射(哈希)到结构指针?

标签 c data-structures hashtable pthreads

我正在使用的编程语言的解释器实现中有一个thread数据类型。由于各种原因,这是一个相当常见的操作,需要获取当前 线程(它本身就是一个指针:struct thread*).

但是,pthread_self(3) 给了我一个 pthread_t,它是一个不透明类型;在某些系统上,它似乎是一个unsigned long,但我听说我不能依赖这种情况。我怀疑哈希表是这种唯一映射的正确实现(pthread_t ID 到struct thread 指针);但是,我不知道如何可靠地散列 pthread_t

我非常感谢任何对 pthread(3) 有更多经验的人的建议,或者实际上,在任何需要“散列”不透明数据类型的情况下。

最佳答案

我认为保存struct thread*的最佳方式是线程本地存储。像这样的东西:

static pthread_key_t struct_thread_key;
pthread_key_create(&struct_thread_key, NULL);

在线程初始化器中:

struct thread *my_thread = malloc(sizeof(*my_thread));
// ...
pthread_setspecific(struct_thread_key, my_thread);

稍后访问当前线程:

struct thread *my_thread = (struct thread *) pthread_getspecific(struct_thread_key);

关于c - 如何将 `pthread_t` 反向映射(哈希)到结构指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3126229/

相关文章:

c - 数组边界在 ']' 标记之前不是整数常量,而实际上它是常量

c - strncmp 的奇怪行为

c - 队列数据结构中 isempty 的线程安全实现

data-structures - 线性探测如何在不中断查找的情况下处理删除?

powershell - 如何检查 PowerShell 变量是否是有序哈希表?

c++ - 具有非唯一键的直接地址表

c - ungetc() 的意外行为

c++ - 在 Macbook Pro 上实现 clang -fno-stack-protector 编译代码时出现问题

C++ : Declaring struct return-type function in header file

java - 数组的 ArrayList 与 ArrayLists 的数组与类似的东西