Monday, May 16, 2016

Thread changing value without use of a global variable.

Some time back I was contemplating how could we have a thread modify a parameter sent to it with the change visible in the caller without using a global variable.
Some searching give a few hints which were a good enough starting point. After some trial and (a lot of) errors, I arrived at the solution below:



You need to include the following: stdio.h,pthread.h,string.h,stdlib.h

struct car{
int servicingNo;
char registrationNo[5];
int engineCapacity;
char color[5];
};


void * calculateCost(void * val){

  struct car c=*(struct car *)val;
float v=c.engineCapacity*2.1;//emulating change of value
float *fee=&v;
pthread_exit(fee);

}


void main(){
pthread_t tid;
struct car arrCar[100];
float cost[100];
int n, i;
printf("How many cars do you have in your garage ?");
scanf("%d",&n);
for(i=0;i struct car tempCar;

tempCar.servicingNo=i;

strcpy(tempCar.registrationNo,"Test");

tempCar.engineCapacity=100*i;

strcpy(tempCar.color,"Red");

pthread_create(&tid,NULL,calculateCost,(void *)&tempCar);

//This is the Magic!!!
float *valRetThread;
pthread_join(tid,(void**)&valRetThread);
arrCar[i]=tempCar;
cost[i]=*valRetThread;

}//input

for(i=0;i printf("\n%d \t %s",arrCar[i].servicingNo,arrCar[i].registrationNo);
printf("\t %d \t %s", arrCar[i].engineCapacity,arrCar[i].color);
printf(" \t owes %f ",cost[i]);
printf("\n");
}

No comments: