fork download
  1. #include <pthread.h>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. void* compute_prime (void* args)
  6. {
  7. int candidate = 2;
  8. int n = *((int*)args);
  9.  
  10. while(1) {
  11. int factor;
  12. int is_prime = 1;
  13. for (factor = 2; factor < candidate; ++factor)
  14. if(candidate % factor == 0) {
  15. is_prime = 0;
  16. break;
  17. }
  18. if(is_prime){
  19. if(--n == 0)
  20. return (void*)candidate;
  21. }
  22. ++candidate;
  23. }
  24. return NULL;
  25. }
  26.  
  27. int main()
  28. {
  29. pthread_t thread;
  30. int which_prime = 5000;
  31. int prime;
  32. pthread_create (&thread, NULL, &compute_prime, &which_prime);
  33.  
  34. pthread_join(thread, (void**)&prime);
  35. printf("The %d th prime number is %d.\n", which_prime, prime);
  36. }
Success #stdin #stdout 2.17s 11656KB
stdin
Standard input is empty
stdout
The 5000 th prime number is 48611.