Problem on threads to calculate prime numbers from start to end

Viewed 55
#include<stdio.h>//-lpthread suppoting library
#include<stdlib.h>
#include<pthread.h>
#include<math.h>

int isPrime(int n){
    for(int i=2;i<=sqrt(n);i++){
        if(n%i==0){
            return 0;
        }
    }
    return 1;
}

void *child(void *param){
    int n=(int)param;
    return (void*)isPrime(n);
}

int main(){
    int start,end,prime;
    printf("Enter start and end for prime number generation:\n");
    scanf("%d %d",&start,&end);
    pthread_t thread[end-start+1];
    for(int i=start,j=0;i<=end;i++,j++){
        pthread_create(&thread[j],0,&child,(void*)i);
        printf("hi");
        pthread_join(thread[j],(void*)&prime);
        if(prime==1){
            printf("%d\t",i);
        }
    }
    return 0;
}

This is the C code I have written so far to list prime numbers from start to end from the user.In a for loop it creates a thread to check if a number is prime or not.Lastly it joins and it returns 1 for prime and 0 for not prime.

But however it only goes through the for loop once for some reason.I don't know what the problem is...

Sample input:Enter start and end for prime number generation: 25 35

Output: hi25

I used hi to check how many times it was looping. I guess only once since it has only one hi.

Expected result: Enter start and end for prime number generation: 25 35

Output: 29 31

0 Answers
Related