Reputation: 824
What I have is a simple code that starts a thread for the purpose of collecting user input and updating the result accordingly:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int x;
void *inc_x(void *x_void_ptr)
{
int *x_ptr = (int *)x_void_ptr;
while(1)
scanf("%d", &x_ptr);
return NULL;
}
int main()
{
int y = 0;
pthread_t thread_ID;
pthread_create(&thread_ID, NULL, &inc_x, &x) ;
while(1)
{
printf("x: %d, y: %d\n", x, y);
sleep(1);
}
return 0;
}
The problem is that X never get's updated, why ?
Upvotes: 0
Views: 2055
Reputation: 4722
code has not the expected behaviour as you write in the x pointer itself instead of x
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int x;
void *inc_x(void *x_void_ptr)
{
int *x_ptr = x_void_ptr; /* no need for cast in C */
while(1)
scanf("%d", x_ptr); /* x_ptr is alread a pointer to x no need for &*/
return NULL;
}
int main()
{
int y = 0;
pthread_t thread_ID;
pthread_create(&thread_ID, NULL, &inc_x, &x) ;
while(1)
{
printf("x: %d, y: %d\n", x, y);
sleep(1);
}
return 0;
}
Nevertheless, you should protect you access with lock as a race exist between the reader and the writer
Upvotes: 1