我正在使用的编程语言的解释器实现中有一个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/