COLOuRSLIDES COLOuRSLIDES - 9 days ago 5
C Question

C - Error while passing structure to threads

Here I have a

struct


struct dotData{
long x;
long y;
};


Which I try to pass to multiple
threads


void *find_z(void *thisdot)
{
long z;
struct dotData *data;
*data = *((struct dotData*)(thisdot));
z = data.x + data.y;
printf("Here's our dot! %ld * %ld = %ld \n", data.x, data.y, z);
pthread_exit(NULL);
}


From
main()
where I create a struct
thisdot
, which is passed as an argument to
find_z
every time its elements
x
and
y
are changed

int main()
{
.
.
.
struct dotData thisdot;

int NUM_THREADS;
NUM_THREADS = N*M;
pthread_t threads[NUM_THREADS];
int i, j;

for(i = 0; i < M; i++){
for (j = 0; j < N; j++) {
thisdot.x = x_dotBegin + x_interval*j;
thisdot.y = y_dotBegin + y_interval*i;
pthread_create(&threads[NUM_THREADS], NULL, find_z, &thisdot);
}
}
pthread_exit(NULL);
}


However, during compilation I get an error in
z = data.x + data.y;


error: request for member ‘x’ in something not a structure or union|
error: request for member ‘y’ in something not a structure or union|


How do I correctly pass this struct to threads?

Answer

The problem is that data is a pointer to a structure, and for those you need to use the "arrow" operator ->, like in data->x.


There is a worse problem though:

struct dotData *data;
*data = *((struct dotData*)(thisdot));

The pointer data doesn't point anywhere. Uninitialized local (non-static) variables will have an indeterminate value. To use a pointer you actually need to make it point somewhere.

Or, for a simple solution and the one I recommend, not use pointers at all:

struct dotData = *(struct dotData *) thisdot;

You also have another big problem, in how you pass data to the threads. All the threads will get the same pointer to the same structure. So the modifications you make in the thread-creation loop will be set for all the data in all the threads.

This can be solved by dynamically allocating the structure you pass to the threads. You can then just copy the pointer instead of copy the structure. And you must remember to free the data or you will have a memory leak.