#include <stdio.h>
#include <pthread.h>
#define NUM_THREADS 5
#define MAXCOUNT 1000000
int shared_variable = 0;
//pthread_mutex_t mutex; // Mutex declaration
void* increment_variable(void* thread_id) {
for (int i = 0; i < MAXCOUNT; i++) {
//pthread_mutex_lock(&mutex); // Lock before updating
shared_variable++;
//pthread_mutex_unlock(&mutex); // Unlock after updating
}
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
//pthread_mutex_init(&mutex, NULL); // Initialize the mutex
for (int i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], NULL, increment_variable, (void*)(size_t)i);
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
printf("Value of shared variable after race condition handling: %d\n", shared_variable
);
//pthread_mutex_destroy(&mutex); // Destroy the mutex
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxwdGhyZWFkLmg+CgojZGVmaW5lIE5VTV9USFJFQURTIDUKI2RlZmluZSBNQVhDT1VOVCAxMDAwMDAwCgppbnQgc2hhcmVkX3ZhcmlhYmxlID0gMDsKLy9wdGhyZWFkX211dGV4X3QgbXV0ZXg7IC8vIE11dGV4IGRlY2xhcmF0aW9uCgp2b2lkKiBpbmNyZW1lbnRfdmFyaWFibGUodm9pZCogdGhyZWFkX2lkKSB7CiAgICBmb3IgKGludCBpID0gMDsgaSA8IE1BWENPVU5UOyBpKyspIHsKICAgICAgICAvL3B0aHJlYWRfbXV0ZXhfbG9jaygmbXV0ZXgpOyAvLyBMb2NrIGJlZm9yZSB1cGRhdGluZwogICAgICAgIHNoYXJlZF92YXJpYWJsZSsrOwogICAgICAgIC8vcHRocmVhZF9tdXRleF91bmxvY2soJm11dGV4KTsgLy8gVW5sb2NrIGFmdGVyIHVwZGF0aW5nCiAgICB9CiAgICBwdGhyZWFkX2V4aXQoTlVMTCk7Cn0KCmludCBtYWluKCkgewogICAgcHRocmVhZF90IHRocmVhZHNbTlVNX1RIUkVBRFNdOwogICA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