The problem of multi-thread variable self-increment in C language

the description is not clear. Please look at the code and the result directly. Thank you.

void * product (void * arg) {

int rear = 0 ;
while(1) {
    rear = (rear + 1)%5;
    printf("p:%d\n",rear);
    Sleep(500);
    } } 

int main (void) {

pthread_t pid;
pthread_create(&pid,NULL,product,NULL);
pthread_join(pid,NULL);
return 0; }

guess that the sequential output should be 0123401234, but this is not the case. Excuse me, what"s going on?

Mar.02,2021

there is no problem with your code running on linux

-sharpinclude <stdio.h>  
-sharpinclude <pthread.h>  

void * product(void *arg){
    int rear = 0 ;
    while(1) {
        rear = (rear + 1)%5;
        printf("p:%d\n",rear);
        sleep(1);
    } 
}

int main(void) {
    pthread_t pid;
    pthread_create(&pid,NULL,product,NULL);
    pthread_join(pid,NULL);
    return 0; 
}

compile

gcc pthread.c -pthread

output

p:0
p:1
p:2
p:3
p:4
p:0
p:1
p:2
p:3
p:4
......

what do you mean by memory overflow? What environmental conditions?


there is a problem under windows. Include windows.h is required under windows, or the Sleep function will use the prototype in winbase.h by default. Sleep and linux under windows are different.. So the address of the rear will change, so running will exceed the size limit of the int type and will overflow.

thanks, man! The problem has been solved.

Menu