Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile warning when returning retval with pthread_exit()

Tags:

c

linux

pthreads

I have the following:

void *Thrd(void *data)
{
    int ret;
    ret = myfunc();
    pthread_exit((void *)ret);
}

int main(int argc, char *argv[])
{
    int status;

    pthread_create(&Thread, NULL, Thrd, &data);

    pthread_join(txThread, (void **)&status);
    if (status)
        printf("*** thread failed with error %d\n", status);
}

It works and I'm able to read status but I'm getting the following warning at compile:

test.cpp: In function ‘void* Thrd(void*)’:
test.cpp:468:26: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

this is the line with pthread_exit()

I simply can't find what is wrong :( ...

like image 780
Meh Avatar asked Mar 12 '26 18:03

Meh


1 Answers

So, you are trying to return an integer value from a thread function. A POSIX thread function can only return void*.

There are a few ways to return a value from another thread:

1) You can cast an integer to void* and back, provided void* is wide enough to hold the value without truncation:

void *Thrd(void *vdata) {
    int value = ...;
    void* thread_return_value = (void*)value;
    return thread_return_value;
}
// ...
void* status;
pthread_join(txThread, &status);
int value = (int)status;

2) Pass the address of the return value to the thread function and make the thread function set that value:

struct Data { int return_value; };

void *Thrd(void *vdata) {
    // ...
    int value = ...;
    struct Data* data = vdata;
    data->return_value = value;
    return NULL;
}
// ...
pthread_create(&Thread, NULL, Thrd, &data);
pthread_join(txThread, NULL);
int value = data->return_value;

3) Let the thread allocate the return value. The other thread that joins() needs to read that value and deallocate it:

void *Thrd(void *vdata) {
    // ...
    int* value = malloc(sizeof *value);
    *value = ...;
    return value;
}
// ...
void* status;
pthread_join(txThread, &status);
int* value = status;
// ...
free(value);
like image 156
Maxim Egorushkin Avatar answered Mar 14 '26 08:03

Maxim Egorushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!