Home > Net >  How do i get a usable int for a switch statement from a void pointer?
How do i get a usable int for a switch statement from a void pointer?

Time:10-31

The parameter 'opt' is passed to my function with pthread_create:

intptr_t num1 = 0;
pthread_create(&t1, NULL, &routine, &num1)

and then I have a switch statement in my function that will print one of two statements depending on the case:

void* routine(void* opt) {
    long int n = (long int)&opt;
    switch(n) {
    case 0: 
        printf("Test 0 from threads\n");
        break;
    case 1: 
        printf("Test 1 from threads\n");
        break;
    };
    sleep(3);
    printf("Ending thread...\n");

    return NULL;
}

That first line of the function is where I'm stuck. I'm trying to get the original value of num1 into 'n' so that I can use it for the switch statement.

CodePudding user response:

The original value you're passing in is a intptr_t *, so that's what you should be reading it as.

intptr_t *n = opt;
switch(*n) {

CodePudding user response:

routine doesn't use the argument in a way that demands the integer be passed by reference at all. That is, you're only using the value of the integer. Since you're already using an intptr_t, you can take advantage of the fact that inptr_ts can be safely converted to pointers and back.

pthread_create(&t1, NULL, routine, (void*)num1);
void *routine(void *opt)
{
    intptr_t n = (intptr_t)opt;
    ...
}

A benefit of this approach is, since you're passing the integer by value, you won't run into a problem if the original variable falls out of scope.

CodePudding user response:

In order to fix the problem, you can change the line

long int n = (long int)&opt;

to:

long int n = *(intptr_t*)opt;

However, this does not seem like the proper solution. The following code does not seem ideal:

intptr_t num1 = 0;
pthread_create(&t1, NULL, &routine, &num1)

It does not seem appropriate to use the type intptr_t (which is designed to hold pointer values as integers) in this case, if, as demonstrated in the question, you only want it to store the values 0 or 1.

You could of course simply use int or long int instead of the data type intptr_t. But I suspect that you selected the data type intptr_t to be able to directly store the value inside a pointer, like this:

intptr_t num1 = 0;
pthread_create(&t1, NULL, &routine, (void*)num1 );

If you do that, then, in the function routine, you can use the line

long int n = (intptr_t)opt;

to convert the pointer back to a number.

The first solution has the disadvantage that you must ensure that the lifetime of the referenced object has not expired, whenever you dereference the pointer. This is not a problem with the second solution.

  • Related