threads
threads copied to clipboard
Not able to generate race condition
I wrote a code using pthreads where multiple threads were accessing and modifying a global variable and race condition should occur without any locking mechanism or atomic operations but it was not the case. Can anyone explain why this did not occur? The code is as follows:
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdbool.h>
#define NTHREADS 150
pthread_t tid[NTHREADS];
int counter;
pthread_mutex_t lock;
int check = 3;
void* trythis(void *arg)
{
unsigned long i = 0;
// pthread_mutex_lock(&lock);
counter += 1;
// pthread_mutex_unlock(&lock);
printf("\n Job %d has started\n", counter);
check+=1;
printf("\n Job %d has finished\n", counter);
check+=1;
return NULL;
}
int main(void)
{
int i = 0;
int error;
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init has failed\n");
return 1;
}
while(i < NTHREADS)
{
error = pthread_create(&(tid[i]), NULL, &trythis, NULL);
if (error != 0)
printf("\nThread can't be created :[%s]", strerror(error));
i++;
}
for(i=0;i<NTHREADS;i++){
pthread_join(tid[i],NULL);
}
pthread_mutex_destroy(&lock);
printf("%d\n",check );
return 0;
}
I think this happens, because some implementations are locking the whole memory length for an atomic operation, thus memory corruption cannot occur per variable (no tear can occur, and all non-atomic operations are in effect atomic). See this #181. But if an implementation does not lock the whole memory for each read/write (load/store) then your program will have the desired race condition. The implementation you use, just provides better memory access guaranties then the specification requires.