Logo 
Search:

C Programming Articles

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

Program to find the sum of numbers from 1 to n using thread

Posted By: Joe Evans     Category: C Programming     Views: 8358

Program to find the sum of numbers from 1 to n using thread.

Code for Program to find the sum of numbers from 1 to n using thread in C Programming

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

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

main()
{
    int iNumber,iCount;
    pthread_t tid;
    printf("Enter Number Up to Which You want to Sum :");
    scanf("%d",&iNumber);    
    pthread_create(&tid,NULL,thread_sum,(void *)&iNumber);
    for(iCount=1;iCount<=iNumber;iCount=iCount+2)
    {
        pthread_mutex_lock(&mVar);
        TotalSum=TotalSum + iCount;
        pthread_mutex_unlock(&mVar);
    }
    
    pthread_join(tid,NULL);
    
    printf("Final Sum is : %d \n",TotalSum);
//    return 0;
}

void *thread_sum(void *no)
{
    int *iNumber,iCount;
    iNumber=(int*)no;
    
    for(iCount=2;iCount<=*iNumber;iCount=iCount+2)
    {
        pthread_mutex_lock(&mVar);
        TotalSum=TotalSum + iCount;
        pthread_mutex_unlock(&mVar);
    }
    pthread_exit(NULL);    
}

/* Output

[divyen@localhost pp-tw4]$ cc -o Prog04 -lpthread Prog04.c
[divyen@localhost pp-tw4]$ ./Prog04
Enter Number Up to Which You want to Sum :10
Final Sum is : 55

*/
  
Share: 



Joe Evans
Joe Evans author of Program to find the sum of numbers from 1 to n using thread is from London, United Kingdom.
 
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!