fork download
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <pthread.h>
  5.  
  6. void* compute_prime (void*);
  7.  
  8. int main() {
  9. pthread_t thread;
  10. int which_prime = 5;
  11. int prime;
  12. pthread_create(&thread,NULL,compute_prime,(void*)&which_prime);
  13. pthread_join(&thread,(void*)&prime);
  14. printf("The %dth prime number is : %d\n",which_prime,prime);
  15. return 0;
  16. }
  17.  
  18. void* compute_prime (void* arg) {
  19. int candidate = 2;
  20.  
  21. int n = *((int*) arg);
  22. // Stores the value of arg in n
  23. while (1) {
  24. bool is_prime = true;
  25. // Here the loop tests to see if the candidate is prime
  26. for (int factor = 2; factor < candidate; ++factor)
  27. if(candidate%factor==0) {
  28. is_prime = false;
  29. break;
  30. }
  31. if(is_prime==true) {
  32. if(--n==0)
  33. return (void*) candidate;
  34. }
  35. ++candidate;
  36. }
  37. return NULL;
  38. }
Success #stdin #stdout 0s 4348KB
stdin
Standard input is empty
stdout
The 5th prime number is : 0