Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdio.h>
- #include <zconf.h>
- #define or ||
- void* isPrime(void* primeCand);
- static int count = 0;
- pthread_mutex_t sem;
- void decrement_count(){
- pthread_mutex_lock(&sem);
- count--;
- pthread_mutex_unlock(&sem);
- }
- int threadCount(){
- int res = 0;
- pthread_mutex_lock(&sem);
- res = count;
- pthread_mutex_unlock(&sem);
- return res;
- }
- void incrementCount(){
- pthread_mutex_lock(&sem);
- count++;
- pthread_mutex_unlock(&sem);
- }
- void initProcess(void* n){
- char good = 1;
- while(good){
- if(threadCount() < 20) {
- pthread_t pthread;
- incrementCount();
- pthread_create(&pthread, NULL, isPrime, n);
- //pthread_detach(pthread);
- //pthread_join(pthread, NULL);
- good = 0;
- }
- else{
- good = 1;
- }
- }
- }
- void* isPrime(void* n){
- long primeCand = (long)n;
- if(primeCand == 0 or primeCand == 1)
- return NULL;
- int i = 2;
- while(i <= primeCand){
- if(primeCand%i == 0)
- break;
- i++;
- }
- if( i == primeCand)
- printf("%li ",primeCand);
- decrement_count();
- }
- int main() {
- long n = 0;
- pthread_mutex_init(&sem,0);
- scanf("%li",&n);
- long k = 0;
- while(k <= n){
- initProcess((void*)k);
- k++;
- }
- sleep(1);
- pthread_mutex_destroy(&sem);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement