fork(1) download
  1. #include <stdio.h>
  2. #include <pthread.h>
  3.  
  4. #define THREADS 5
  5.  
  6. int shared = 0;
  7. pthread_mutex_t lock;
  8.  
  9. void* increment(void* arg) {
  10. for(int i = 0; i < 100000; i++) {
  11. pthread_mutex_lock(&lock);
  12. shared++;
  13. pthread_mutex_unlock(&lock);
  14. }
  15. return NULL;
  16. }
  17.  
  18. int main() {
  19. pthread_t threads[THREADS];
  20.  
  21. pthread_mutex_init(&lock, NULL);
  22.  
  23. for(int i = 0; i < THREADS; i++) {
  24. pthread_create(&threads[i], NULL, increment, NULL);
  25. }
  26.  
  27. for(int i = 0; i < THREADS; i++) {
  28. pthread_join(threads[i], NULL);
  29. }
  30.  
  31. pthread_mutex_destroy(&lock);
  32.  
  33. printf("Final value of shared variable = %d\n", shared);
  34.  
  35. return 0;
  36. }
Success #stdin #stdout 0.02s 5288KB
stdin
5
stdout
Final value of shared variable = 500000