Click here to Skip to main content
15,888,977 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Write a multithreaded program that calculates the sum of a list of numbers. This program will be passed a series of numbers (5 Numbers exactly) on the command line at the run time and will then create one worker thread that will find the sum of the 5 values, while the parent thread will output (print) the sum value once the worker thread has exited. The variable representing the sum will be stored globally. For example, suppose your program is passed the integers: 7 8 9 10 11 The program will show the following output: The sum is 45.

and i solved that i will put the answer in the last but the part 2 of the example i cant understand it and cant solve it please help:

Modify your code in part (a) by dividing the sum job between two threads. Each thread will be passed the 5 numbers, then the first thread will sum up the even numbers only (i.e. 8 and 10 in the previous example), while the second thread will sum up the odd numbers (i.e. 7, 9, 11 in the previous example). The summation is being done on the same sum global variable. Another global variable called counter is used to count the numbers (even or odd) that have been summed up. The value of counter is incremented and then printed out every time a number (even or odd) is added to the sum variable. The parent thread will output (print) the final sum value and the final counter value once the worker threads have exited. The program will show the following output for the previous example (note that TN is either 1 or 2) : The counter value is 1 and incremented by thread TN

What I have tried:

C
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>

/*Error handling for pthread_create and pthread_join*/
/*from the pthread_create man page*/
#define handle_error_en(en, msg) \
        do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

/* # of running threads */
volatile int running_threads = 0;

pthread_t thread[1]; /*Descriptors for our 3 threads*/

int numOfElements;/*Total # of elements from the user*/

struct Results{ /*Struct to hold the statistical results*/
	

	int sum;

}Results;



/*This function finds the average of an array*/
void *findsum(void *array_ptr){
	
	int i;	 /*counter*/

	int *elements = (int*)array_ptr; 	/*re reference void array pointer*/

	for(i = 0; i < numOfElements; i++){		/*iterate through array*/

		Results.sum += elements[i];		/*add element @ i to average*/

	}


	running_threads -= 1;	/*Decrement running threads counter*/

return NULL;

}

/* This method accepts a int n(initial size of array) and
   pointer to an array and returns # of elements in the array
*/
int getArrayInput(int n, int *array_ptr){
		
		int input;/*Store user input */

		int numberOfElements = 0;/*Number of Integers inputed*/

    	printf("Creating Dynamic Array...\n-\n");

		for(;;){  /*infinite loop*/

    		printf("Enter a positive value:\nNegative Number to Stop\n-\n");
   
    		//Get Int from console, store at address of input

			if (scanf("%d",&input) != 1){

				printf("\nOops that wasn't an Integer\nlets try filling the array again\nRemember INTEGERS only!\n");

				exit(EXIT_FAILURE);
			
			}

    		if (input >= 0){ 

       		 	if (numberOfElements == n){

          	  	  n += 1; //Make room for the current input
            		
          		  array_ptr = realloc(array_ptr, n * sizeof(int));//realloc array and set pointer
            
       			 }

        		array_ptr[numberOfElements++] = input;//Store input at next empty element
    
    		} else {
        
       		 printf("\nNumber of Integers: %d\n", numberOfElements);
       
       		 break;

   				 }

			}

	return numberOfElements;
	
		}


	
/*This function creates the 3 threads we need and supplys
  error catching for pthread_create, it could be 
  modified easily to create any # of threads automatically
*/
void createThreads(int *array_ptr){
	
	int s; /*error #*/
	 /*Create a thread and passing in the function to begin 
	 exectuing as well as that functions required arguments*/ 
 
 
	 /*Create a thread and passing in the function to begin 
	 exectuing as well as that functions required arguments*/ 
	 s = pthread_create(&thread[2], NULL, findsum, (void *)array_ptr);
	 		 
		 if (s != 0){

           handle_error_en(s, "pthread_create");
       	
       	 }
			
			running_threads += 1;

}

/* The main function initialiazes the dynamic array as well
   as allocating space for it, Then it creates, using pthread_create,
   1 threa to calculate the min, 
 */
int main(){

	int n = 1; /* Initial Array Size*/

	int *array_ptr = malloc(n * sizeof(int));/*Initialize array pointer*/
		
		 /*get an n sized array of elements from the user and save count*/
		 numOfElements = getArrayInput(n, array_ptr);
		
		 createThreads(array_ptr);
		
	    	while(running_threads>0){	/*Wait for each thread to decrement*/
	
				sleep(1);

			}

	

		/*Prompt the user with our results*/
		printf("\nThe sum is %d\n",Results.sum);

	return(0);

}
Posted
Updated 25-Nov-17 1:23am
v2
Comments
OriginalGriff 25-Nov-17 5:55am    
What part of it don't you understand? It's pretty clear - perhaps you should speak to your tutor?
Member 13540542 25-Nov-17 7:07am    
how can i modify my code to do part b
i don't have a tutor i am learning alone at home this question was an example i found and i tried to solve i solved part (a) to find the sum of 5 numbers and it was easy but part (b) wants me to modify part (a) to find the sum of odd and even number i tried to solve it but it seems i cant modify the code i wrote to find the solution of part (b
)

1 solution

You need to create two threads, each with a different task: one adds even numbers, one add odd. You will need to add the global variable, and provide locking to ensure that the two threads don;t get in a mess while using it.
You will also need to provide a signaling mechanism that gets the main thread to display the current (revised) count.

To be honest, if you are trying to learn to code by finding examples and trying to do them, you are pretty much wasting your time. That's like trying to learn to drive by stealing a car and driving the wrong way up the motorway. You may learn a lot, you will probably crash a significant number of times, but you won't learn how to parallel park, or what to do at a roundabout! And you certainly won't be a competent driver, even after a few dozen trips...
Development is the same: "learning on your own" just means you have no idea what you don't know - and a lot of it could make your job a lot easier. Back to the car analogy, assume you steal a stick shift / manual gearbox but you don't even know that the clutch exists, much less what to do with it. Learning to drive from a book or better a course will teach you those things - and learn to code the same way will also "fill in the gaps" a lot better.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900