Write a segment of code which will do the following Declare a structure which co
ID: 3936754 • Letter: W
Question
Write a segment of code which will do the following Declare a structure which contains two integer values, start and end Declare a thread which will take in a pointer to the structure declared previously and will sum the numbers between start and end and then will add the result to the value sum Write a main function which will invoke two threads, passing in the values of 1 and 10 and 11 and 20 as start and end values The main will wait for both threads to terminate and then will print the sum out to the console d Be sure to properly synchronize all critical segmentsExplanation / Answer
#include <pthread.h>
#include <stdio.h>
/* Global Variable, sum, to add results of all threads */
int sum = 0;
/* Structure declaration containing two data members, start and end */
struct start_end
{
int start;
int end;
};
/* Function to add start and end values and add result to sum */
void* sum_print (void* parameters)
{
struct start_end* p = (struct start_end*) parameters;
int i, result;
result = 0;
/* Add the values between start and end values inclusive of both */
for (i = (p->start); (i <= p->end); i++)
result = result + i;
/* Add the result to the global variable, sum */
sum = sum + result;
return NULL;
}
/* The main() function */
int main ()
{
pthread_t tid1;
pthread_t tid2;
struct start_end thread1_args;
struct start_end thread2_args;
/* Create thread 1 to pass start and end values as 1 and 10, respectively. */
thread1_args.start = 1;
thread1_args.end = 10;
pthread_create (&tid1, NULL, &sum_print, &thread1_args);
/* Create thread 2 to pass start and end values as 11 and 20, respectively. */
thread2_args.start = 11;
thread2_args.end = 20;
pthread_create (&tid2, NULL, &sum_print, &thread2_args);
/* Ensure both the threads has finished execution. */
pthread_join (tid1, NULL);
pthread_join (tid2, NULL);
/* Now print the final result. */
printf(“The total sum of thread 1 and thread 2 is: %d “, sum);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.