cmultithreadingc11

passing local variable to thrd_create


Imagine this:

int foo(void* arg) {
    int v = *(int*)arg; // is arg a potential dangling pointer here?
}

thrd_t t;

int bar() {
   int my_variable = 42;
   int ret = thrd_create(&t,foo,&my_variable);
   return ret;
}

what is the order of execution here? Since foo runs on a different thread and we do not actually wait for the thread to finish/join - but thrd_create returns - is arg a potential dangling pointer?


Solution

  • In this case there might be a dangling pointer... It depends on if the thread run and copy the value before the bar function returns (where the life-time of my_variable ends). So what you have is a data race.

    A better idea, if you want to pass only the value, is to use some explicit conversions to pass the value itself as a value:

    thrd_create(..., (void *) (intptr_t) my_variable);
    

    And

    int foo(void *arg)
    {
        int value = (int) (intptr_t) arg;
        // ...
    }