SlideShare a Scribd company logo
Part 1)
#include
#include
#include
#include
/*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[3]; /*Descriptors for our 3 threads*/
int numOfElements;/*Total # of elements from the user*/
struct Results{ /*Struct to hold the statistical results*/
int min;
int max;
int average;
}Results;
/*This function finds the minimum element of an array*/
void *findMin(void *array_ptr){
int i; /*counter*/
int *elements = (int*)array_ptr; /*re reference void array pointer*/
Results.min = elements[0]; /*set minimum to first element */
for(i = 0; i < numOfElements; i++){ /*iterate through array*/
if(elements[i] < Results.min){ /*if the current element is less than the current min*/
Results.min = elements[i]; /*store the new min*/
}
}
running_threads -= 1; /*Decrement thread count*/
return NULL;
}
/*This function finds the maximum element of an array*/
void *findMax(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*/
if(elements[i] > Results.max){ /*store the new max*/
Results.max = elements[i];
}
}
running_threads -= 1; /*Decrement thread count*/
return NULL;
}
/*This function finds the average of an array*/
void *findAverage(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.average += elements[i]; /*add element @ i to average*/
}
Results.average = Results.average/numOfElements; /*Divide the sum by the number of
elements*/
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... - ");
for(;;){ /*infinite loop*/
printf("Enter a positive value: Negative Number to Stop - ");
//Get Int from console, store at address of input
if (scanf("%d",&input) != 1){
printf(" Oops that wasn't an Integer lets try filling the array again Remember
INTEGERS only! ");
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(" Number of Integers: %d ", numberOfElements);
break;
}
}
return numberOfElements;
}
/*This function joins our n number of threads */
void joinThreads(int numberOfThreads){
int i; /*count*/
int s; /*error #*/
while(numberOfThreads >= 0){ /*Join our threads*/
s = pthread_join(thread[numberOfThreads], NULL);
/*if we recieve anything other than 0 we have a join error*/
if (s != 0){
/*handle error*/
handle_error_en(s, "pthread_create");
}
numberOfThreads--;
}
}
/*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*/
s = pthread_create(&thread[0], NULL, findMin, (void *)array_ptr);
if (s != 0){
handle_error_en(s, "pthread_create");
}
running_threads += 1;
/*Create a thread and passing in the function to begin
exectuing as well as that functions required arguments*/
s = pthread_create(&thread[1], NULL, findMax, (void *)array_ptr);
if (s != 0){
handle_error_en(s, "pthread_create");
}
running_threads += 1;
/*Create a thread and passing in the function to begin
exectuing as well as that functions required arguments*/
s = pthread_create(&thread[2], NULL, findAverage, (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,
3 Threads 1 to calculate the min, the max, and the average.
We then wait until each thread completes its task and then
join the 3 threads and prompt the user with the results
*/
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);
}
joinThreads(2); /*Call our thread joining function passing # of threads */
/*Prompt the user with our results*/
printf(" The average is %d The maximum is %d The minimum is %d ",Results.average,
Results.max, Results.min);
return(0);
}
Solution
Part 1)
#include
#include
#include
#include
/*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[3]; /*Descriptors for our 3 threads*/
int numOfElements;/*Total # of elements from the user*/
struct Results{ /*Struct to hold the statistical results*/
int min;
int max;
int average;
}Results;
/*This function finds the minimum element of an array*/
void *findMin(void *array_ptr){
int i; /*counter*/
int *elements = (int*)array_ptr; /*re reference void array pointer*/
Results.min = elements[0]; /*set minimum to first element */
for(i = 0; i < numOfElements; i++){ /*iterate through array*/
if(elements[i] < Results.min){ /*if the current element is less than the current min*/
Results.min = elements[i]; /*store the new min*/
}
}
running_threads -= 1; /*Decrement thread count*/
return NULL;
}
/*This function finds the maximum element of an array*/
void *findMax(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*/
if(elements[i] > Results.max){ /*store the new max*/
Results.max = elements[i];
}
}
running_threads -= 1; /*Decrement thread count*/
return NULL;
}
/*This function finds the average of an array*/
void *findAverage(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.average += elements[i]; /*add element @ i to average*/
}
Results.average = Results.average/numOfElements; /*Divide the sum by the number of
elements*/
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... - ");
for(;;){ /*infinite loop*/
printf("Enter a positive value: Negative Number to Stop - ");
//Get Int from console, store at address of input
if (scanf("%d",&input) != 1){
printf(" Oops that wasn't an Integer lets try filling the array again Remember
INTEGERS only! ");
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(" Number of Integers: %d ", numberOfElements);
break;
}
}
return numberOfElements;
}
/*This function joins our n number of threads */
void joinThreads(int numberOfThreads){
int i; /*count*/
int s; /*error #*/
while(numberOfThreads >= 0){ /*Join our threads*/
s = pthread_join(thread[numberOfThreads], NULL);
/*if we recieve anything other than 0 we have a join error*/
if (s != 0){
/*handle error*/
handle_error_en(s, "pthread_create");
}
numberOfThreads--;
}
}
/*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*/
s = pthread_create(&thread[0], NULL, findMin, (void *)array_ptr);
if (s != 0){
handle_error_en(s, "pthread_create");
}
running_threads += 1;
/*Create a thread and passing in the function to begin
exectuing as well as that functions required arguments*/
s = pthread_create(&thread[1], NULL, findMax, (void *)array_ptr);
if (s != 0){
handle_error_en(s, "pthread_create");
}
running_threads += 1;
/*Create a thread and passing in the function to begin
exectuing as well as that functions required arguments*/
s = pthread_create(&thread[2], NULL, findAverage, (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,
3 Threads 1 to calculate the min, the max, and the average.
We then wait until each thread completes its task and then
join the 3 threads and prompt the user with the results
*/
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);
}
joinThreads(2); /*Call our thread joining function passing # of threads */
/*Prompt the user with our results*/
printf(" The average is %d The maximum is %d The minimum is %d ",Results.average,
Results.max, Results.min);
return(0);
}

More Related Content

PDF
Modify this code to use multiple threads with the same data1.Modif.pdf
PPTX
OPERATNG SYSTEM MODULE-2 PRESENTATION OS
PPT
PDF
GPU Programming on CPU - Using C++AMP
PDF
Multithreaded Programming Part- II.pdf
PDF
Consider the fork_examplec code under Example code for pr.pdf
PDF
Parallel Programming
PDF
40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf
Modify this code to use multiple threads with the same data1.Modif.pdf
OPERATNG SYSTEM MODULE-2 PRESENTATION OS
GPU Programming on CPU - Using C++AMP
Multithreaded Programming Part- II.pdf
Consider the fork_examplec code under Example code for pr.pdf
Parallel Programming
40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf

Similar to Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf (20)

PDF
System Programming - Threading
PPTX
P-Threads
PDF
Data Structure using C
PPTX
shared_memory_c_program_in_Parallel Computing .pptx
PPTX
Shared memory C program in Parallel Com.pptx
PPTX
array ppt of c programing language for exam
PDF
Unix Programs
DOCX
Data structures
PPT
Os Reindersfinal
PPT
Os Reindersfinal
PDF
PDF
operating system linux,ubuntu,Mac#include iostream #include .pdf
PPTX
Array,MULTI ARRAY, IN C
TXT
Bankers Algo Implementation
PDF
I have come code already but I cant quite get the output rig.pdf
PPT
Unit 4
DOCX
Parallel programming Comparisions
PDF
C lab programs
PDF
C lab programs
PPT
Shared Memory Programming with Pthreads (1).ppt
System Programming - Threading
P-Threads
Data Structure using C
shared_memory_c_program_in_Parallel Computing .pptx
Shared memory C program in Parallel Com.pptx
array ppt of c programing language for exam
Unix Programs
Data structures
Os Reindersfinal
Os Reindersfinal
operating system linux,ubuntu,Mac#include iostream #include .pdf
Array,MULTI ARRAY, IN C
Bankers Algo Implementation
I have come code already but I cant quite get the output rig.pdf
Unit 4
Parallel programming Comparisions
C lab programs
C lab programs
Shared Memory Programming with Pthreads (1).ppt

More from mohammadirfan136964 (20)

PDF
2. Ligamentum arteriosumThe aortic arch loops over the left pulmo.pdf
PDF
moles should be equal to complete consumption so.pdf
PDF
TrueOne of the fundamental rules which control the PLSS system is .pdf
PDF
The stronger the attractions betweenparticles (mo.pdf
PDF
a. It gives benzalacetone b. acetone will underg.pdf
PDF
what is the mean, median, mode and the midrange for 191, 167,257,1.pdf
PDF
Disodium malonate is an ionic sodium salt that is soluble in water..pdf
PDF
They showed that GFP protein could be expressed in the organisms wit.pdf
PDF
Thepossible mechanism by which a 75kD nuclear protein is imported in.pdf
PDF
The neurons are nervous cells which play the central role in generat.pdf
PDF
The parts of the respiratory tract which have nonkeratinized stratif.pdf
PDF
The impact of Brexit would be visible on the financial instituations.pdf
PDF
The alkaline earth metals burn in oxygen to form the monoxide, MO wh.pdf
PDF
Squid molluscCrab ArthropodsCrayfish ArthropodsPolychaete .pdf
PDF
The code you written is little bit confusing and lengthy. Here is th.pdf
PDF
Ques-1Normala flora and microbiota of nose and mouth are non-infe.pdf
PDF
Solution.According to IASB framework INCOME is the one of element .pdf
PDF
7. Answer is A.Cytochromes are protien containing iron or heme gro.pdf
PDF
A and C. RGB analog component video uses no compression, imposes no .pdf
PDF
Public key authentication is the most secure colution and utilizes a.pdf
2. Ligamentum arteriosumThe aortic arch loops over the left pulmo.pdf
moles should be equal to complete consumption so.pdf
TrueOne of the fundamental rules which control the PLSS system is .pdf
The stronger the attractions betweenparticles (mo.pdf
a. It gives benzalacetone b. acetone will underg.pdf
what is the mean, median, mode and the midrange for 191, 167,257,1.pdf
Disodium malonate is an ionic sodium salt that is soluble in water..pdf
They showed that GFP protein could be expressed in the organisms wit.pdf
Thepossible mechanism by which a 75kD nuclear protein is imported in.pdf
The neurons are nervous cells which play the central role in generat.pdf
The parts of the respiratory tract which have nonkeratinized stratif.pdf
The impact of Brexit would be visible on the financial instituations.pdf
The alkaline earth metals burn in oxygen to form the monoxide, MO wh.pdf
Squid molluscCrab ArthropodsCrayfish ArthropodsPolychaete .pdf
The code you written is little bit confusing and lengthy. Here is th.pdf
Ques-1Normala flora and microbiota of nose and mouth are non-infe.pdf
Solution.According to IASB framework INCOME is the one of element .pdf
7. Answer is A.Cytochromes are protien containing iron or heme gro.pdf
A and C. RGB analog component video uses no compression, imposes no .pdf
Public key authentication is the most secure colution and utilizes a.pdf

Recently uploaded (20)

PPTX
GDM (1) (1).pptx small presentation for students
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Classroom Observation Tools for Teachers
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Pre independence Education in Inndia.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Cell Types and Its function , kingdom of life
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
GDM (1) (1).pptx small presentation for students
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Classroom Observation Tools for Teachers
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Pre independence Education in Inndia.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
Cell Types and Its function , kingdom of life
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
human mycosis Human fungal infections are called human mycosis..pptx
O5-L3 Freight Transport Ops (International) V1.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Supply Chain Operations Speaking Notes -ICLT Program
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
RMMM.pdf make it easy to upload and study
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Microbial diseases, their pathogenesis and prophylaxis

Part 1)#include stdio.h #include stdlib.h #include pthrea.pdf

  • 1. Part 1) #include #include #include #include /*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[3]; /*Descriptors for our 3 threads*/ int numOfElements;/*Total # of elements from the user*/ struct Results{ /*Struct to hold the statistical results*/ int min; int max; int average; }Results; /*This function finds the minimum element of an array*/ void *findMin(void *array_ptr){ int i; /*counter*/ int *elements = (int*)array_ptr; /*re reference void array pointer*/ Results.min = elements[0]; /*set minimum to first element */ for(i = 0; i < numOfElements; i++){ /*iterate through array*/ if(elements[i] < Results.min){ /*if the current element is less than the current min*/ Results.min = elements[i]; /*store the new min*/ } } running_threads -= 1; /*Decrement thread count*/ return NULL;
  • 2. } /*This function finds the maximum element of an array*/ void *findMax(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*/ if(elements[i] > Results.max){ /*store the new max*/ Results.max = elements[i]; } } running_threads -= 1; /*Decrement thread count*/ return NULL; } /*This function finds the average of an array*/ void *findAverage(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.average += elements[i]; /*add element @ i to average*/ } Results.average = Results.average/numOfElements; /*Divide the sum by the number of elements*/ 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... - ");
  • 3. for(;;){ /*infinite loop*/ printf("Enter a positive value: Negative Number to Stop - "); //Get Int from console, store at address of input if (scanf("%d",&input) != 1){ printf(" Oops that wasn't an Integer lets try filling the array again Remember INTEGERS only! "); 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(" Number of Integers: %d ", numberOfElements); break; } } return numberOfElements; } /*This function joins our n number of threads */ void joinThreads(int numberOfThreads){ int i; /*count*/ int s; /*error #*/ while(numberOfThreads >= 0){ /*Join our threads*/ s = pthread_join(thread[numberOfThreads], NULL);
  • 4. /*if we recieve anything other than 0 we have a join error*/ if (s != 0){ /*handle error*/ handle_error_en(s, "pthread_create"); } numberOfThreads--; } } /*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*/ s = pthread_create(&thread[0], NULL, findMin, (void *)array_ptr); if (s != 0){ handle_error_en(s, "pthread_create"); } running_threads += 1; /*Create a thread and passing in the function to begin exectuing as well as that functions required arguments*/ s = pthread_create(&thread[1], NULL, findMax, (void *)array_ptr); if (s != 0){ handle_error_en(s, "pthread_create"); } running_threads += 1;
  • 5. /*Create a thread and passing in the function to begin exectuing as well as that functions required arguments*/ s = pthread_create(&thread[2], NULL, findAverage, (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, 3 Threads 1 to calculate the min, the max, and the average. We then wait until each thread completes its task and then join the 3 threads and prompt the user with the results */ 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); } joinThreads(2); /*Call our thread joining function passing # of threads */ /*Prompt the user with our results*/ printf(" The average is %d The maximum is %d The minimum is %d ",Results.average, Results.max, Results.min); return(0); }
  • 6. Solution Part 1) #include #include #include #include /*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[3]; /*Descriptors for our 3 threads*/ int numOfElements;/*Total # of elements from the user*/ struct Results{ /*Struct to hold the statistical results*/ int min; int max; int average; }Results; /*This function finds the minimum element of an array*/ void *findMin(void *array_ptr){ int i; /*counter*/ int *elements = (int*)array_ptr; /*re reference void array pointer*/ Results.min = elements[0]; /*set minimum to first element */ for(i = 0; i < numOfElements; i++){ /*iterate through array*/ if(elements[i] < Results.min){ /*if the current element is less than the current min*/ Results.min = elements[i]; /*store the new min*/ } }
  • 7. running_threads -= 1; /*Decrement thread count*/ return NULL; } /*This function finds the maximum element of an array*/ void *findMax(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*/ if(elements[i] > Results.max){ /*store the new max*/ Results.max = elements[i]; } } running_threads -= 1; /*Decrement thread count*/ return NULL; } /*This function finds the average of an array*/ void *findAverage(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.average += elements[i]; /*add element @ i to average*/ } Results.average = Results.average/numOfElements; /*Divide the sum by the number of elements*/ 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 */
  • 8. int numberOfElements = 0;/*Number of Integers inputed*/ printf("Creating Dynamic Array... - "); for(;;){ /*infinite loop*/ printf("Enter a positive value: Negative Number to Stop - "); //Get Int from console, store at address of input if (scanf("%d",&input) != 1){ printf(" Oops that wasn't an Integer lets try filling the array again Remember INTEGERS only! "); 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(" Number of Integers: %d ", numberOfElements); break; } } return numberOfElements; } /*This function joins our n number of threads */ void joinThreads(int numberOfThreads){ int i; /*count*/ int s; /*error #*/
  • 9. while(numberOfThreads >= 0){ /*Join our threads*/ s = pthread_join(thread[numberOfThreads], NULL); /*if we recieve anything other than 0 we have a join error*/ if (s != 0){ /*handle error*/ handle_error_en(s, "pthread_create"); } numberOfThreads--; } } /*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*/ s = pthread_create(&thread[0], NULL, findMin, (void *)array_ptr); if (s != 0){ handle_error_en(s, "pthread_create"); } running_threads += 1; /*Create a thread and passing in the function to begin exectuing as well as that functions required arguments*/ s = pthread_create(&thread[1], NULL, findMax, (void *)array_ptr); if (s != 0){ handle_error_en(s, "pthread_create");
  • 10. } running_threads += 1; /*Create a thread and passing in the function to begin exectuing as well as that functions required arguments*/ s = pthread_create(&thread[2], NULL, findAverage, (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, 3 Threads 1 to calculate the min, the max, and the average. We then wait until each thread completes its task and then join the 3 threads and prompt the user with the results */ 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); } joinThreads(2); /*Call our thread joining function passing # of threads */ /*Prompt the user with our results*/ printf(" The average is %d The maximum is %d The minimum is %d ",Results.average, Results.max, Results.min);