fork download
  1. #include <stdio.h>
  2. #include <pthread.h>
  3.  
  4. #define NUM_THREADS 5
  5. #define MAXCOUNT 1000000
  6.  
  7. int shared_variable = 0;
  8. //pthread_mutex_t mutex; // Mutex declaration
  9.  
  10. void* increment_variable(void* thread_id) {
  11. for (int i = 0; i < MAXCOUNT; i++) {
  12. //pthread_mutex_lock(&mutex); // Lock before updating
  13. shared_variable++;
  14. //pthread_mutex_unlock(&mutex); // Unlock after updating
  15. }
  16. pthread_exit(NULL);
  17. }
  18.  
  19. int main() {
  20. pthread_t threads[NUM_THREADS];
  21. //pthread_mutex_init(&mutex, NULL); // Initialize the mutex
  22.  
  23. for (int i = 0; i < NUM_THREADS; i++) {
  24. pthread_create(&threads[i], NULL, increment_variable, (void*)(size_t)i);
  25. }
  26.  
  27. for (int i = 0; i < NUM_THREADS; i++) {
  28. pthread_join(threads[i], NULL);
  29. }
  30.  
  31. printf("Value of shared variable after race condition handling: %d\n", shared_variable);
  32.  
  33. //pthread_mutex_destroy(&mutex); // Destroy the mutex
  34. return 0;
  35. }
  36.  
Success #stdin #stdout 0s 5268KB
stdin
Standard input is empty
stdout
Value of shared variable after race condition handling: 5000000