我所拥有的是一个简单的代码,它启动一个线程以收集用户输入并相应地更新结果:
#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;
}
问题是X永远不会更新,为什么?
答案 0 :(得分:1)
代码没有预期的行为
#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;
}
尽管如此,当读者和作家之间存在种族时,你应该用锁来保护你的访问权