João Marques João Marques - 1 month ago 10
C Question

Why typedef doesnt work with pthread?

Basicaly im trying to send a typdef trought a function, however it seems i cant...

Basicaly I'm trying to send a typdef trought a function, however it seems I can't...

#define MAX 2
typedef struct
{
unsigned long myPid;
unsigned long parentPid;
unsigned long myTid;
} myProperties;

void* funcproperties(void* arg);
void createthread(myProperties (*properties)[MAX]);


So this is how my typdef is defined...

void* funcproperties(void* arg)
{
myProperties *properties=(myProperties*) arg;
properties->myPid=getpid();
properties->parentPid=getppid();
properties->myTid=syscall(SYS_gettid);
return NULL;
}


If I give values to properties[0].myPid=getpid(), i wont have problems, however when i send the address of the position where the typedef will start(0 or 1), it doenst, i wonder why? Maybe pthread doesnt support it?

void createthread(myProperties (*properties)[MAX])
{
pthread_t tids[MAX];

for (int i = 0; i < MAX; i++) {
if ((errno = pthread_create(&tids[i], NULL, funcproperties, properties[i])) != 0)
ERROR(C_ERRO_PTHREAD_CREATE, "pthread_create() failed!");
}
for (int i = 0; i < MAX; i++)
printf("\n PID:%lu DAD: %lu TID: %lu", properties[i]->myPid, properties[i]->parentPid ,properties[i]->myTid);
}


This is the result im getting(i force pid to define, however: (If im not mistaken im getting random values).

PID:0 DAD: 3076323888 TID: 134519979
PID:612976384 DAD: 3077911516 TID: 3220212208
PID:0 DAD: 3076323888 TID: 134519979
PID:612976384 DAD: 3077911516 TID: 3220212208
PID:0 DAD: 3076323888 TID: 134519979
PID:612976384 DAD: 3077911516 TID: 3220212208
I 9292 did my job now make yourself served


ps:(im also using processes)

Answer

You must ensure that it is impossible for one thread to access an object while another thread might be modifying it. You have not done this, so the results are unpredictable.

One solution would be to call pthread_join on all the threads before looking at the values they are setting.