I’m trying to write some code using posix threads but I’m stuck from the first step and to be honest I can’t realise why. I know that my problem has probably to do with some sort of synchronisation but I can’t figure it out.
What I have in main is the following:
while(1){
int x = getX();
pthread_t t;
printf("Main: %d\n",x);
pthread_create(&t, NULL, process_x, &x);
}
When I try to print the x value from the main and also the process_x function what I get is something like this:
Main: 1
Main: 2
Main: 3
Main: 4
Main: 5
Process_x: 5
What do I miss here?
—- EDIT —–
OK, maybe I need to provide some more info. The getX function receives data from a socket and returns an identifier while for our needs now the process_x just prints the argument it receives.
Apparently using malloc doesn’t work because it sets x to 0 so the process always reads 0. But thanks to everyones ideas I finally made it work using a condition variable and now everything is ok. Here is the code.