Search code examples
cmultithreadingpthreadsrace-conditioncritical-section

Producing Race Condition


I am trying to produce a race condition (assuming that there exists a critical section in the csfunc) with the following sample code:

#include <stdio.h>
#include <pthread.h>
  
int cs = 0;

void* csfunc(void* arg){

    for (int i = 0; i < 1000000; i++){

        cs++;
        cs--;

        if (cs!=0){
        
            printf("cs: %d\n", cs);
        }
    }
}
  
  
int main(){
    
    for (int i = 0; i < 100; i++){

        pthread_t t;
        pthread_create(&t,NULL,csfunc,NULL);
        pthread_join(t,NULL);
    }
    return 0;
}

I assume that 100 threads with 1000000 iterations are enough to do a lot of race conditions. Nonetheless, my code is not producing even one single printing of the value of cs. Any ideas? Or am I missing something?

PS> Please note that I am using the gcc compiler with the following command

gcc cs.c -lpthread -o cs

Solution

  • When you do join, it waits until that thread is finished then continues the loop. So you should put thread handles in an array and wait for all of them.

    pthread_t handles[100];
    for (int i = 0; i < 100; i++){
        pthread_create(&handles[i],NULL,csfunc,NULL);
    }
    for (int i = 0; i < 100; ++i)
        pthread_join(handes[i],NULL);