Question

In: Computer Science

C Programming Language Question The following program sums up a number from a user input argv[1]...

C Programming Language Question

The following program sums up a number from a user input argv[1] by using a single thread. For example, argv[1] of 100 is going to give us a sum of 5050 using just a single thread.

I need to modify it so that it takes 2 command lines args, argv[2] for number of threads. In other words, the program needs to use multi-threads to solve it. The number of threads is going to divide the work between them and then join together to sum the numbers.

For example, a command line of 100 10 will give us a sum of 5050 using 10 threads.

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

int sum; // this data is shared by the threads
void *runner(void *param); // threads call this function

int main(int argc, char *argv[])
{
pthread_t tid; // thread identifier
pthread_attr_t attr; // set of thread attributes

// set the default attributes of the thread
pthread_attr_init(&attr);
// create the thread
pthread_create(&tid, &attr, runner, argv[1]);
// wait for the thread to exit
pthread_join(tid, NULL);

printf("Sum = %d\n", sum);
}

void *runner(void *param)
{
int i, upper = atoi(param);
sum = 0;

for (int i = 1; i <= upper; i++)
sum += i;

pthread_exit(0);
}

Solutions

Expert Solution

Please look at my code and in case of indentation issues check the screenshots.

---------------main.c-----------------

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

struct range
{
   //create a structure to pass as parameter to the thread
   int tid;   //The structure contains thread id, the and the range of numbers to compute sum
   int start;
   int end;
   int sum;
};

void *runner(void *param);   // threads call this function

int main(int argc, char *argv[])
{
   if (argc != 3)
   {
       printf("Incorrect number of command line arguments. Sample Usage: ./a.out 100 10 \n");
       exit(0);
   }

   int N = atoi(argv[1]);
   int N_OF_THREADS = atoi(argv[2]);
   pthread_t tids[N_OF_THREADS];   //create thread ids as array
   pthread_attr_t attr;   // set of thread attributes
   pthread_attr_init(&attr);   // set the default attributes of the thread

   int status, i;
   int prev = 0;
   struct range *r = malloc(sizeof(struct range) *N_OF_THREADS);   //create array of structures
   for (i = 0; i < N_OF_THREADS; i++)   //loop for number of threads
   {
       printf("\nMain. Creating thread %d", i);

       r[i].tid = i;   //update the thread id
       r[i].start = prev + 1;   //update the range for according to the thread id
       r[i].end = r[i].start + N / N_OF_THREADS - 1;
       prev = r[i].end;
       if (i == N_OF_THREADS - 1)
           r[i].end = N;

       status = pthread_create(&tids[i], &attr, runner, &r[i]);   //start the thread, pass structure parameter
       if (status)
       {
           printf("Error %d\n", status);
           exit(-1);
       }
   }

   for (i = 0; i < N_OF_THREADS; i++)
   {
       pthread_join(tids[i], NULL);   //main waits for thread i to exit
   }

   int total = 0;
   for (i = 0; i < N_OF_THREADS; i++)
   {
       total = total + r[i].sum;   //main adds the sum of the values computed by the threads
   }
   printf("\n\nThe sum of numbers from 1 to %d is %d\n", N, total);   //print total
   exit(0);
}

void *runner(void *param)   // threads call this function
{
   struct range *ptr = (struct range *) param;   //get the structure parameter as pointer
   int sum = 0;
   int i;
   for (i = ptr->start; i <= ptr->end; i++)   //compute the sum from start to end
       sum = sum + i;
   //print threaad output
   printf("\nThread %d computed sum from %d to %d, SUM = %d", ptr->tid, ptr->start, ptr->end, sum);
   ptr->sum = sum;   //store the sum inside the structure sum field
   pthread_exit(NULL);
}

--------------Screenshots--------------------

------------------Output------------------

---------------Updated answer---------------------------------------------------------------

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

struct range
{
   //create a structure to pass as parameter to the thread
   int tid;   //The structure contains thread id, the and the range of numbers to compute sum
   int start;
   int end;
   int sum;
};

void *runner(void *param);   // threads call this function

int main(int argc, char *argv[])
{
   if (argc != 3)
   {
       printf("Incorrect number of command line arguments. Sample Usage: ./a.out 100 10 \n");
       exit(0);
   }

   int N = atoi(argv[1]);
   int N_OF_THREADS = atoi(argv[2]);
   pthread_t tids[N_OF_THREADS];   //create thread ids as array
   pthread_attr_t attr;   // set of thread attributes
   pthread_attr_init(&attr);   // set the default attributes of the thread

   int status, i;
   int prev = 0;
   struct range *r = malloc(sizeof(struct range) *N_OF_THREADS);   //create array of structures
   for (i = 0; i < N_OF_THREADS; i++)   //loop for number of threads
   {
       printf("\nMain. Creating thread %d", i);

       r[i].tid = i;   //update the thread id
       r[i].start = prev + 1;   //update the range for according to the thread id
       r[i].end = r[i].start + N / N_OF_THREADS - 1;
       prev = r[i].end;
       if (i == N_OF_THREADS - 1)
           r[i].end = N;

       status = pthread_create(&tids[i], &attr, runner, &r[i]);   //start the thread, pass structure parameter
       pthread_join(tids[i], NULL);   //main waits for all the threads to exit
       if (status)
       {
           printf("Error %d\n", status);
           exit(-1);
       }
   }

   /*for (i = 0; i < N_OF_THREADS; i++)
   {
       pthread_join(tids[i], NULL);   //main waits for thread i to exit
   }*/

   int total = 0;
   for (i = 0; i < N_OF_THREADS; i++)
   {
       total = total + r[i].sum;   //main adds the sum of the values computed by the threads
   }
   printf("\n\nThe sum of numbers from 1 to %d is %d\n", N, total);   //print total
   exit(0);
}

void *runner(void *param)   // threads call this function
{
   struct range *ptr = (struct range *) param;   //get the structure parameter as pointer
   int sum = 0;
   int i;
   for (i = ptr->start; i <= ptr->end; i++)   //compute the sum from start to end
       sum = sum + i;
   //print threaad output
   printf("\nThread %d computed sum from %d to %d, SUM = %d", ptr->tid, ptr->start, ptr->end, sum);
   ptr->sum = sum;   //store the sum inside the structure sum field
   pthread_exit(NULL);
}

-------------------------------------------------------------------------------------------------------
Please give a thumbs up if you find this answer helpful.
If it doesn't help, please comment before giving a thumbs down.
Please Do comment if you need any clarification.
I will surely help you.


Related Solutions

Using the C Programming language, write a program that sums an array of 50 elements. Next,...
Using the C Programming language, write a program that sums an array of 50 elements. Next, optimize the code using loop unrolling. Loop unrolling is a program transformation that reduces the number of iterations for a loop by increasing the number of elements computed on each iteration. Generate a graph of performance improvement. Tip: Figure 5.17 in the textbook provides an example of a graph depicting performance improvements associated with loop unrolling. Marking:- Optimize the code for an array of...
c# language Write a program that takes in a number from the user. Then it prints...
c# language Write a program that takes in a number from the user. Then it prints a statement telling the user if the number is even or odd. If the number is odd, it counts down from the number to 0 and prints the countdown on the screen, each number on a new line. If the number is even, it counts down from the number to 0, only even numbers. For example, if the user enters 5, the output will...
Lab 1 Write a program in the C/C++ programming language to input and add two fractions...
Lab 1 Write a program in the C/C++ programming language to input and add two fractions each represented as a numerator and denominator. Do not use classes or structures. Print your result (which is also represented as a numerator/denominator) to standard out. If you get done early, try to simplify your result with the least common denominator. The following equation can be used to add fractions: a/b + c/d = (a*d + b*c)/(b*d) Example: 1/2 + 1/4 = ( 1(4)...
C# Programming Language Write a C# program ( Console or GUI ) that prompts the user...
C# Programming Language Write a C# program ( Console or GUI ) that prompts the user to enter the three examinations ( test 1, test 2, and test 3), homework, and final project grades then calculate and display the overall grade along with a message, using the selection structure (if/else). The message is based on the following criteria: “Excellent” if the overall grade is 90 or more. “Good” if the overall grade is between 80 and 90 ( not including...
C programming Get a number from the user and write a program that checks to see...
C programming Get a number from the user and write a program that checks to see if the inputted number is equal to x*x+x and x must be greater than 0. For example, if the user inputs 12. The program should check to see if 12 = x*x+x. In this case it is true because 3*3+3 = 12.
Create a basic program (C programming language) that accomplishes the following requirements: Allows the user to...
Create a basic program (C programming language) that accomplishes the following requirements: Allows the user to input 2 numbers, a starting number x and ending number y Implements a while loop that counts from x (start) to y(end). Inside the loop, print to the screen the current number Print rather the current number is even or odd If the number is even , multiply by the number by 3 and print the results to the screen. If the number is...
in the c programming language input is given in the form The input will be of...
in the c programming language input is given in the form The input will be of the form [number of terms] [coefficient k] [exponent k] … [coefficient 1] [exponent 1] eg. 5 ─3 7 824 5 ─7 3 1 2 9 0 in this there are 5 terms with -3x^7 being the highest /* Initialize all coefficients and exponents of the polynomial to zero. */ void init_polynom( int coeff[ ], int exp[ ] ) { /* ADD YOUR CODE HERE...
THE FOLLOWING QUESTION IS FOR C PROGRAMMING LANGUAGE Printing the decimal equivalent of a binary number....
THE FOLLOWING QUESTION IS FOR C PROGRAMMING LANGUAGE Printing the decimal equivalent of a binary number. Write a program that accepts an integer (5 digits or fewer) containing only 0s and 1s (i.e., binary) and prints out its decimal equivalent using the remainder and division operator to select the "binary" digits one at a time. Make sure your input is tested for multiple options: incorrect characters, too many, too few, etc. I need help making this program. No loops, if...
C PROGRAMMING LANGUAGE PROBLEM TITLE : ARRAY usually, if people want to input number into an...
C PROGRAMMING LANGUAGE PROBLEM TITLE : ARRAY usually, if people want to input number into an array, they will put it from index 0 until N - 1 using for. But, Bibi is bored to code like that. So, she didin't want to input the number that way. So Bibi challenged you to make a program that will read a sequence (represent index) that she made, then input the number to an array but input it with the same sequence...
Objective: Write this program in the C programming language Loops with input, strings, arrays, and output....
Objective: Write this program in the C programming language Loops with input, strings, arrays, and output. Assignment: It’s an organization that accepts used books and then sells them a couple of times a year at book sale events. Some way was needed to keep track of the inventory. You’ll want two parallel arrays: one to keep track of book titles, and one to keep track of the prices. Assume there will be no more than 10 books. Assume no more...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT