Reputation: 55
I'm working on a project in which I have to use a structure of pointers as input arguments into a thread. My code looks something like this:
struct coord
{
double* xPos;
double* yPos;
};
void cdecl foo( void* inData)
{
coord* my_data = (coord*) inData;
printf("Thread values:\n");
printf("xVal: %f\n", *(my_data->xPos) );
printf("yVal: %f\n", *(my_data->yPos) );
}
and the main's body looks something like this:
{
double startX = 10;
double startY = 10;
/* declare variables to hold the incoming values */
coord inData;
inData.xPos = &startX;
inData.yPos = &startY;
printf("Initial values:\n");
printf("xVal: %f\n", *(inData.xPos) );
printf("yVal: %f\n", *(inData.yPos) );
_beginthread( foo, 0, (void*) &inData );
}
Why is my program displaying different values for the main and thread, and how do I correct it?
Upvotes: 1
Views: 116
Reputation: 122391
You are declaring your structure and double values on the stack and once that method returns (after _beginthread()
returns) the stack is removed leading to undefined behaviour.
You need to allocate the structure on the heap, including the double
values. You'll also need to manage this allocated memory.
Also, I don't see why you are using double *
as opposed to simply double
.
EDIT: Some sample code. This allocates the structure on the heap and passes the allocated data back to the caller. There is still some work to do with thread synchronization, which is outside the scope of this question:
struct coord
{
double xPos;
double yPos;
};
void cdecl foo(void* inData)
{
coord* my_data = (coord*) inData;
printf("Thread values:\n");
printf("xVal: %f\n", my_data->xPos);
printf("yVal: %f\n", my_data->yPos);
}
coord *startThread()
{
coord *inData = new coord;
inData->xPos = 10;
inData->yPos = 10;
_beginthread( foo, 0, (void*) inData );
return inData;
}
int main()
{
coord *data = startThread();
printf("Initial values:\n");
printf("xVal: %f\n", data->xPos);
printf("yVal: %f\n", data->yPos);
// TODO: wait for thread
return 0;
}
Upvotes: 3