Advertisement
Guest User

Untitled

a guest
Jun 29th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <cmath>
  4. #include <pthread.h>
  5. #include <malloc.h>
  6.  
  7. #define RET_CODE(n) (void*)(n)
  8. #define PRIME_RANGE 0xFFFF
  9. #define THR_NUM 10
  10.  
  11. pthread_mutex_t lock,flock;
  12. uint idx=2,n=0;
  13.  
  14. void* calculator(void* arg)
  15. {
  16.     uint i,k=1,z=0;
  17.     bool is_prime = false;
  18.     uint* primes = (uint*)calloc(PRIME_RANGE,
  19.         sizeof(uint));
  20.     if(!primes)
  21.     {
  22.         perror("calloc primes");
  23.         RET_CODE(1);
  24.     }
  25.     while(idx<0xFFFFFFFF)
  26.     {
  27.         pthread_mutex_lock(&lock);
  28.         i = idx;
  29.         idx+=PRIME_RANGE;
  30.         pthread_mutex_unlock(&lock);
  31.         for(;i<(i+PRIME_RANGE); i++)
  32.         {
  33.             is_prime = true;
  34.             for(uint j=2;j<=(uint)sqrt(i);j++)
  35.             {
  36.                 if(j==i||i%j==0)
  37.                 {
  38.                     is_prime = false;
  39.                     break;
  40.                 }
  41.             }
  42.             if(is_prime)
  43.             {
  44.                 if(z<PRIME_RANGE)
  45.                     primes[z++] = i;
  46.                 else
  47.                 {
  48.                     pthread_mutex_lock(&flock);
  49.                     FILE* fp = fopen(
  50.                      "/storage/emulated/0/prime.txt","ab");
  51.                     for(uint c=0;c<z;c++)
  52.                     {
  53.                         fprintf(fp,"%u\t",
  54.                             primes[c]);
  55.                         if((c+1)%5==0)
  56.                             putc('\n',fp);
  57.                     }
  58.                     fclose(fp);
  59.                     printf("Prmes N %d\n",(n+=z));
  60.                     pthread_mutex_unlock(&flock);
  61.                     z=0;
  62.                 }
  63.             }
  64.         }
  65.     }
  66.     free(primes);
  67.     RET_CODE(0);
  68. }
  69.  
  70. int main()
  71. {
  72.     pthread_t thr[THR_NUM];
  73.    
  74.     pthread_mutex_init(&lock,NULL);
  75.     pthread_mutex_init(&flock,NULL);
  76.    
  77.     for(uint l=0;l<THR_NUM;l++)
  78.         pthread_create(&thr[l],NULL,calculator,
  79.             NULL);
  80.     getc(stdin);
  81.    
  82.     pthread_mutex_destroy(&lock);
  83.     pthread_mutex_destroy(&flock);
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement