The following program shows that we can use return() or pthread_exit() to return a void* variable that is available to pthread_join()'s status variable.
(1) Should there be a preference for using one over the other?
(2) Why does using return() work? Normally we think of return putting a value on the stack but since the thread is completed the stack should vanish. Or does the stack not get destroyed until after pthread_join()?
(3) In your work, do you see much use of the status variable? It seems 90% of the code I see just NULLs out the status parameter. Since anything changed via the void* ptr is already reflected in the calling thread there doesn't seem much point to returning it. Any new void* ptr returned would have to point to something malloc-ed by the start thread, which leaves the receiving thread with the responsibility to dispose of it. Am I wrong in thinking the status variable is semi-pointless?
#include <iostream>
#include <pthread.h>
using namespace std;
struct taskdata
{
int x;
float y;
string z;
};
void* task1(void *data)
{
taskdata *t = (taskdata *) data;
t->x += 25;
t->y -= 4.5;
t->z = "Goodbye";
return(data);
}
void* task2(void *data)
{
taskdata *t = (taskdata *) data;
t->x -= 25;
t->y += 4.5;
t->z = "World";
pthread_exit(data);
}
int main(int argc, char *argv[])
{
pthread_t threadID;
taskdata t = {10, 10.0, "Hello"};
void *status;
cout << "before " << t.x << " " << t.y << " " << t.z << endl;
//by return()
pthread_create(&threadID, NULL, task1, (void *) &t);
pthread_join(threadID, &status);
taskdata *ts = (taskdata *) status;
cout << "after task1 " << ts->x << " " << ts->y << " " << ts->z << endl;
//by pthread_exit()
pthread_create(&threadID, NULL, task2, (void *) &t);
pthread_join(threadID, &status);
ts = (taskdata *) status;
cout << "after task2 " << ts->x << " " << ts->y << " " << ts->z << endl;
}
With output of:
before 10 10 Hello
after task1 35 5.5 Goodbye
after task2 10 10 World