Write a segment of code which will do the following Declare
Solution
#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;
}

