简体   繁体   中英

Updating global variable from a thread

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM