简体   繁体   中英

How do I return a value from thread function?

I have a struct like this:

struct data{
    int x;
    int y;
}

and I have a thread function that looks like this:

void *threadFunction(void *item){
    data *myData = (data*) item;
    int first = 50;
    int second = 10;
    myData->x = first;
    myData->y = second;
    return(void*) myData;
}

I call the thread function like this in main():

pthread_create(threadID, NULL, threadFunction, &item);

but when I want to get the values from my thread function back into main() using this:

struct data* returnedItem;
pthread_join(threadID, (void**) returnedItem;
cout << returnedItem->x << returnedItem->y;

I'm not sure what happens as my program seems to just do nothing. It compiles and runs, but it loops infinitely somewhere or just waits on something. I'm not sure what happens at all, I just don't get any sort of response. What am I doing wrong? Is there something I'm missing in main() to retrieve the value from the pthread_join statement? Maybe I screwed up the arguments in the statement?

You're getting your pointers confused. Do it like this:

void * p;
pthread_join(threadID, &p);
data * returnedItem = static_cast<data *>(p);

While it's possible to convert pointers from and to void pointers, you can't just pretend that a variable of type X (in your case data * ) is actually a variable of type Y (in your case void * ). That's not allowed and undefined behaviour.

pthread_join in its second argument take a pointer to a void* to return result of thread, so you write pthread_join(threadID, (void**) returnedItem ); . But think about it:

struct data* returnedItem;
// what is the value of returnedItem?? possibly garbage, lets say it is 0xFEDCBA98
pthread_join(threadID, (void**) returnedItem );

You cast that garbase into (void**), now at some point pthread_join want to write the result of the thread into argument that provided by you so it say

* (void**) 0xFEDCBA98 = thread_return_value;

but wait! you make pthread_join to deference an invalid pointer and it may even generate something like segmentation fault or worse overwrite one of your most important information! So every time that a function need room to return something, you must provide a valid memory for it. Valid code can be:

pthread_join(threadID, (void**) &returnedItem );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM