是否可以将指针强制转换为unsigned int,然后将其转换回指针?我正在尝试将指针存储到pthread_t变量中的结构,但我似乎无法让它工作。这是我的代码的一些片段(我正在创建一个用户级线程管理库)。当我尝试打印出线程的tid时,它会给我一些很长的垃圾编号。
编辑:没关系,我让它发挥作用。
我改变了
thread = (pthread_t) currentThread;
到
*thread = (pthread_t) currentThread;
认为这是愚蠢的事情。
测试程序:
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, NULL, runner, NULL);
pthread_create(&thread2, NULL, runner, NULL);
pthread_join(&thread2, NULL);
我的图书馆:
typedef struct queueItem
{
int tid;
ucontext_t context;
int caller;
struct queueItem *joiningOn;
struct queueItem *nextContext;
} queueItem;
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)
{
thread = (pthread_t) currentThread;
}
...
int pthread_join(pthread_t thread, void **retval)
{
queueItem *t = (queueItem *) thread;
if(runningContext->joiningOn != NULL) // Current thread is already waiting on another
return EINVAL;
if(t == NULL) // If thread to join on is invalid
return 0;
fprintf(stdout, "JOINEE: %d\n", t->tid); // Prints weird number
runningContext->caller = JOIN;
runningContext->joiningOn = t;
swapcontext(&(runningContext->context), &scheduleContext);
}
答案 0 :(得分:5)
没有。在许多系统上,指针类型大于int类型。如果您在使用pthread_t时遇到问题,请询问它,int不是答案。
例如,在我的机器上,代码如下:
#include <stdio.h>
int main() {
printf("unsigned int = %lu\n", sizeof(unsigned int));
printf("pointer = %lu\n", sizeof(void*));
return 0;
}
输出:
unsigned int = 4
pointer = 8
答案 1 :(得分:4)
如果你确定你的unsigned int与你系统上的void *相同,那么肯定是可能的。
如果您的某些代码无效,请将其发布。
修改:您应该阅读intptr_t
,例如在这里:Why / when to use `intptr_t` for type-casting in C?