Logo 
Search:

C Programming Articles

Submit Article
Home » Articles » C Programming » Parallel Processing ProgramsRSS Feeds

Program to find the total no of prime numbers between 1 to n by using thread

Posted By: Lu Fischer     Category: C Programming     Views: 9213

Program to find the total no of prime numbers between 1 to n by using thread.

Code for Program to find the total no of prime numbers between 1 to n by using thread in C Programming

# include <stdio.h>
# include <pthread.h>


void * thread_sum(void *);
int TotalCount=0;
int iNumber;
pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER;

int main()
{
    int iCount,jCount;
    int threadPara;
    int PrimeFlag=1;
    pthread_t tid;
    printf("Enter Number Up to Which You want to Count Prime Numbers :");
    scanf("%d",&iNumber);
    threadPara=iNumber/2 + 1;
    pthread_create(&tid,NULL,thread_sum,(void *)&threadPara);
    for(iCount=2;iCount<=iNumber/2;iCount=iCount++)
    {
        for(jCount=2;jCount<iCount;jCount++)
        {
            if(iCount%jCount==0)
            {
                PrimeFlag=0;
                break;
            }
        }
        
        if(PrimeFlag==1)
        {    
            printf("[ %d ]  Main\n",iCount);
            pthread_mutex_lock(&mVar);
            TotalCount=TotalCount++;
            pthread_mutex_unlock(&mVar);
        }
        else
        {
            PrimeFlag=1;
        }
    }
    
    pthread_join(tid,NULL);
    
    printf("Final Count is : %d \n",TotalCount);
    return 0;
}

void *thread_sum(void *no)
{
    int *ifrom,iCount,jCount;
    int PrimeFlag=1;
    ifrom=(int*)no;
    
    for(iCount=*ifrom;iCount<=iNumber;iCount=iCount++)
    {
        for(jCount=2;jCount<iCount;jCount++)
        {
            if(iCount%jCount==0)
            {
                PrimeFlag=0;
                break;
            }
        }
        
        if(PrimeFlag==1)
        {    
            printf("[ %d ] Thread\n",iCount);
            pthread_mutex_lock(&mVar);
            TotalCount++;
            pthread_mutex_unlock(&mVar);
        }        
        PrimeFlag=1;        
    }
    pthread_exit(NULL);    
}

/* Output

[divyen@localhost pp-tw4]$ cc -o Prog05 -lpthread Prog05.c
[divyen@localhost pp-tw4]$ ./Prog05
Enter Number Up to Which You want to Count Prime Numbers :20
[ 11 ] Thread
[ 13 ] Thread
[ 17 ] Thread
[ 19 ] Thread
[ 2 ] Main
[ 3 ] Main
[ 5 ] Main
[ 7 ] Main
Final Count is : 8

*/
  
Share: 



Lu Fischer
Lu Fischer author of Program to find the total no of prime numbers between 1 to n by using thread is from Frankfurt, Germany.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!