Guest User

Code

a guest
Nov 27th, 2017
487
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <iostream>
  2. #include <time.h>
  3. #include <pthread.h>
  4.  
  5. using namespace std;
  6.  
  7. int n,k;
  8. bool isPrime[1000010];
  9.  
  10. //Method to generate primes
  11. //The implementation could've been done more efficiently but it was implemented this way
  12. //so that the execution time difference gets amplified further so the distinction is clear.
  13. void *genPrimes(void *arg){
  14.     long rem=(long)arg;
  15.     for(int i=rem;i<n;i+=k)
  16.         if(i>1){
  17.             int factorCnt=0;
  18.             for(int j=1;j<=i;++j)
  19.                 if(!(i%j))
  20.                     ++factorCnt;
  21.             if(factorCnt==2)
  22.                 isPrime[i]=true;
  23.         }
  24.     pthread_exit(NULL);
  25. }
  26.  
  27. //Driver method
  28. int main(){
  29.     //Required variables
  30.     clock_t start,end;
  31.     time_t t;
  32.     srand((unsigned)time(&t));
  33.     float execTime=0;
  34.  
  35.     //Taking input
  36.     cout<<"Enter the number N : ";
  37.     cin>>n;
  38.  
  39.     cout<<"Enter the number of threads : ";
  40.     cin>>k;
  41.  
  42.     //Thread array
  43.     pthread_t threads[k];
  44.  
  45.     //creating threads and assigning them work
  46.     start=clock();
  47.     for(int i=0;i<k;++i)
  48.         pthread_create(&threads[i], NULL, genPrimes, (void *)i);
  49.  
  50.     for(int i=0;i<k;++i)
  51.         pthread_join(threads[i],NULL);
  52.     end=clock();
  53.  
  54.     execTime=((double)(end-start)/CLOCKS_PER_SEC);
  55.  
  56.     cout<<endl<<"The primes are : "<<endl;
  57.     for(int i=0;i<=n;++i)
  58.         if(isPrime[i])
  59.             cout<<i<<" ";
  60.     cout<<endl;
  61.     cout<<endl<<"Execution time is : "<<execTime<<endl;
  62.     return 0;
  63. }
Add Comment
Please, Sign In to add comment