Storing pointer address in unsigned int in C

Is it possible to point a pointer to an unsigned int, and then return it back to a pointer? I am trying to save a pointer to a structure in the pthread_t variable, but I cannot get it to work. Here are some snippets of my code (I am creating a user level flow control library). When I try to print a stream stream, it gives me a long trash number.

Edit: Nothing, I got him to work.

I changed

thread = (pthread_t) currentThread;

to

*thread = (pthread_t) currentThread;

Thought it was something stupid.


Testing program:

pthread_t thread1;
pthread_t thread2;

pthread_create(&thread1, NULL, runner, NULL);
pthread_create(&thread2, NULL, runner, NULL);
pthread_join(&thread2, NULL);

My library:

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);
}
+5
source share
2 answers

I am sure that if you make sure that your unsigned int is the same size as void * on your system.

If you have code that doesn't work, submit it.

: intptr_t, . : / ` intptr_t` C?

+3

. , 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
+5

All Articles