c - 从线程更新全局变量

标签 c multithreading pthreads global-variables

我拥有的是一个简单的代码,它启动一个线程来收集用户输入并相应地更新结果:

#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/

相关文章:

c - 处理 CTRL C 时错过错误 "fatal flex scanner internal error--end of buffer"

c - 指向函数及其返回类型 (void) 的指针

java - 运行处理程序时出现问题?

Android Espresso waitFor.. 和 Thread.sleep() 解决方案

linux - 单一提供者,单一消费者。哪个适合条件变量 : pthread_cond_t, sem_t 或 pthread_mutex_t?

c - pthread 根据用户输入中断线程循环

c - 用 C 语言进行 Win32 API 控制台编程

c - 如何通过 C 中的递归排列来更改叶位置字符串?

java - 使用 volatile long 有什么意义吗?

c++ - Linux 上的 pthread_cancel() 导致异常/核心转储,为什么?