我拥有的是一个简单的代码,它启动一个线程来收集用户输入并相应地更新结果:
#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 永远不会更新,为什么?
最佳答案
当您在 x 指针本身而不是 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;
}
尽管如此,您应该使用锁来保护您的访问,因为读者和作者之间存在竞争
关于c - 从线程更新全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33500991/