作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我拥有的是一个简单的代码,它启动一个线程来收集用户输入并相应地更新结果:
#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/
我是一名优秀的程序员,十分优秀!