0

The following code is about the classical producer and consumer problem and there is a race condition here. When I run this example in MinGW in Windows 10, we have a very large probability (e.g., 80%) of having an inconsistent result. However, when I run it in Ubuntu, the probability is extremely low.

Besides, when I run a similar code in Java, the probability of having an inconsistent result is also very high.

So, could anyone explain what is different behind. I think it is because of different scheduling mechanisms and different time slice settings.

#include <stdio.h>
#include <pthread.h>
int count = 0;
void *producer(){
    for(int i = 0;i<10000;i++)
        count++;
}
void *consumer()  {
    for(int i = 0;i<10000;i++)
        count--;
}
int main(int argc, const char *argv[]){
    printf("initial count: %d\n",count);
    pthread_t t1, t2;
    pthread_create(&t1, NULL, producer,NULL);
    pthread_create(&t2, NULL, consumer,NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    printf("final count: %d\n",count);
    return 0;
}
Quanwang
  • 1
  • 2

0 Answers0