/********************************************************************

                  Example 2 (pthreads_Sumn.c)

Objective                   : To calculate the sum of first n integers.
                              Demonstrates the usage of:
                              pthread_create()
                              pthread_join()
                              pthread_mutex_t
                              pthread_mutex_lock()
                              pthread_mutex_unlock()

Input                       : Number of threads

Output                      : Sum of the first Inout number of threads.

 ********************************************************************/ 


#include<pthread.h>

pthread_mutex_t mutex_sum = PTHREAD_MUTEX_INITIALIZER;

int             sum = 0;



void           *
Addup(int Id)
{
	
	
	pthread_mutex_lock(&mutex_sum);
	
	{
		
			sum += Id;
		
	} 
		
		pthread_mutex_unlock(&mutex_sum);
	
		return;
	
} 


main(int argc, char *argv[])
{
	
		
		pthread_t * threads;
	
		
		int             i, NumThreads;
	
		
		if (argc != 2) {
		
			
			printf(" Missing Argument: Number of Threads.\n");
		
			return;
		
	} 
		
		NumThreads = abs(atoi(argv[1]));
	
		if (NumThreads == 0)
		
			NumThreads = 10;
	
		printf("\n The Number of threads is %d.\n", NumThreads);
	
		
		threads = (pthread_t *) malloc(sizeof(pthread_t) * NumThreads);
	
		
		for (i = 0; i < NumThreads; i++)
		
			
			pthread_create(&threads[i], NULL, (void *(*) (void *)) Addup, (void *) (i + 1));
	
		
		for (i = 0; i < NumThreads; i++)
		
			
			pthread_join(threads[i], NULL);
	
		
		printf("\n Number of threads: %d. Sum: %d.\n", NumThreads, sum);
	
		return;
	
} 
