OBJECTIVES

To develop a C program to compute the sum of all array elements using multithreading.

PROBLEM

You are to use the Ubuntu operating system to create a C program to compute the sum of all elements of an array of integers. Your solution is to use the pthread library and process arrays with 8 integers only. Your solution must also create two threads to process the array. Each thread will process half of the array. You may use the sample code provided as well as the code structure included.

INPUT FORMAT

Your solution is to read from stdin the 8 integers to populate the array.

OUTPUT FORMAT

Your output should follow the format outlined below:

Prompt> The sum of the array elements is: The Sum of All Integers Provided by your solution

SAMPLE CODE

/*
* Assume your file is named t0.c
* To compile: gcc -lpthread t0.c
* To run: ./a.out
*/
#include < stdio.h>
#include < stdlib.h>
#include < pthread.h>
void *printMessage( void *ptr );
int main()
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
/* Creates two threads. Each will execute function */
iret1 = pthread_create( &thread1, NULL, printMessage,
(void*) message1);
iret2 = pthread_create( &thread2, NULL, printMessage,
(void*) message2);
/* Wait until threads are complete before main continues. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Thread 1 returns: %dn",iret1);
printf("Thread 2 returns: %dn",iret2);
exit(0);
}
void *printMessage( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
}

CODE TO HELP YOU DEVELOP YOUR SOLUTION

#include < pthread.h>
#include < stdio.h>
#include < stdlib.h>
#define NUM_THREADS 2
void *ArraySum( void * data )
{
// your code for the ArraySum
}
int main (int argc, char* argv[])
{
int j, sum = 0;
pthread_tsumThreads[NUM_THREADS];
InitializeArray( Your array arguments ); // get values into your array with this function.
for (j = 0; j < NUM_THREADS; j++)
{
int *threadNum;
threadNum = &j;
pthread_create( &sumThreads[j], NULL, ArraySum, (void *)threadNum);
}
for (j = 0; j < NUM_THREADS; j++)
{
pthread_join(tHandles[j], NULL);
sum += gSum[j];
}
printf("The sum of array elements is %d\n", sum);
return( 0 ) ;
}
Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.