Write program to calculate sum of n numbers using thread library.


#include<iosteram.h>
#include <pthread.h>
#include <iostream>
#include <cstdlib>


void *adder(void * number);


unsigned long sum;

int main(int argc, char *argv[])
{
    if (argc != 2) {
        cerr << "Usage: sum <integer value>" << endl;
        exit(1);
    }

    unsigned long number = atol(argv[1]);
    if (number < 0) {
        cerr << "Argument " << number << " must be non-negative." << endl;
        exit(1);
    }
 
    pthread_t tid;
    pthread_attr_t attr;
 
    pthread_attr_init(&attr);

 
    pthread_create(&tid,&attr,adder,(void *) number);
 
    pthread_join(tid,NULL);
 
    cout << "Sum(" << 1 << ", " << number << ") = " << sum << endl;
 
    return 0;
}

void *adder(void * number)
{
    cout << "Thread ID = " << pthread_self() << endl;

    unsigned long num = (unsigned long) number;
    for (int i = 1; i <= num; i++)
    {
        sum += i;
    }
 
    pthread_exit(0);
}

Comments