开发者

How can I reverse-map (hash) `pthread_t`s to structure pointers?

开发者 https://www.devze.com 2023-01-04 17:17 出处:网络
I have a thread datatype in the interpreter implementation for a programming language I am working on. For various reasons, it’s a fairly common operation, to need to get the current thread (which is

I have a thread datatype in the interpreter implementation for a programming language I am working on. For various reasons, it’s a fairly common operation, to need to get the current thread (which is, itself, a pointer: a struct thread*).

However, pthread_self(3) hands me a pthread_t, which is an opaque type; on some systems, it开发者_如何转开发 seems to be an unsigned long, but I hear I can’t depend on that being the case. I suspect a hash table is the proper implementation of this unique mapping (pthread_t ID to struct thread pointer); however, I have no idea how to hash the pthread_t reliably.

I would appreciate advice from anybody with more experience with pthread(3) or, really, any situation wherein you have to “hash” an opaque datatype.


I think the best way to hold your struct thread* is thread-local storage. Something like:

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

In the thread initalizer:

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

To access the current thread later:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号