fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #define THREADS 3
  5. pthread_mutex_t lock;
  6. int shared_counter = 0;
  7. void* factorial(void* arg) {
  8. int num = *(int*)arg;
  9. long long fact = 1;
  10. for(int i = 1; i <= num; i++) {
  11. fact *= i;
  12. }
  13. printf("Factorial of %d = %lld\n", num, fact);
  14. pthread_mutex_lock(&lock);
  15. shared_counter++;
  16. pthread_mutex_unlock(&lock);
  17. return NULL;
  18. }
  19. int main() {
  20. pthread_t threads[THREADS];
  21. int numbers[THREADS] = {5, 6, 7};
  22. pthread_mutex_init(&lock, NULL);
  23. for(int i = 0; i < THREADS; i++) {
  24. if(pthread_create(&threads[i], NULL, factorial, &numbers[i]) != 0) {
  25. printf("Thread creation failed\n");
  26. return 1;
  27. }
  28. }
  29. for(int i = 0; i < THREADS; i++) {
  30. pthread_join(threads[i], NULL);
  31. }
  32. printf("All threads completed.\n");
  33. printf("Shared Counter = %d\n", shared_counter);
  34. pthread_mutex_destroy(&lock);
  35. return 0;
  36. }
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
Factorial of 7 = 5040
Factorial of 6 = 720
Factorial of 5 = 120
All threads completed.
Shared Counter = 3