Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <cmath>
- #include <pthread.h>
- #include <malloc.h>
- #define RET_CODE(n) (void*)(n)
- #define PRIME_RANGE 0xFFFF
- #define THR_NUM 10
- pthread_mutex_t lock,flock;
- uint idx=2,n=0;
- void* calculator(void* arg)
- {
- uint i,k=1,z=0;
- bool is_prime = false;
- uint* primes = (uint*)calloc(PRIME_RANGE,
- sizeof(uint));
- if(!primes)
- {
- perror("calloc primes");
- RET_CODE(1);
- }
- while(idx<0xFFFFFFFF)
- {
- pthread_mutex_lock(&lock);
- i = idx;
- idx+=PRIME_RANGE;
- pthread_mutex_unlock(&lock);
- for(;i<(i+PRIME_RANGE); i++)
- {
- is_prime = true;
- for(uint j=2;j<=(uint)sqrt(i);j++)
- {
- if(j==i||i%j==0)
- {
- is_prime = false;
- break;
- }
- }
- if(is_prime)
- {
- if(z<PRIME_RANGE)
- primes[z++] = i;
- else
- {
- pthread_mutex_lock(&flock);
- FILE* fp = fopen(
- "/storage/emulated/0/prime.txt","ab");
- for(uint c=0;c<z;c++)
- {
- fprintf(fp,"%u\t",
- primes[c]);
- if((c+1)%5==0)
- putc('\n',fp);
- }
- fclose(fp);
- printf("Prmes N %d\n",(n+=z));
- pthread_mutex_unlock(&flock);
- z=0;
- }
- }
- }
- }
- free(primes);
- RET_CODE(0);
- }
- int main()
- {
- pthread_t thr[THR_NUM];
- pthread_mutex_init(&lock,NULL);
- pthread_mutex_init(&flock,NULL);
- for(uint l=0;l<THR_NUM;l++)
- pthread_create(&thr[l],NULL,calculator,
- NULL);
- getc(stdin);
- pthread_mutex_destroy(&lock);
- pthread_mutex_destroy(&flock);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement