Question

In: Computer Science

Modify the sum_thread.cpp program to compute sum = 1 + 1/2 + 1/3 + 1/4 +...

Modify the sum_thread.cpp program to compute sum = 1 + 1/2 + 1/3 + 1/4 + … 1/n.

Let’s estimate natural using n = 20.

sum_thread.cpp

#include <chrono>
#include <iostream>
#include <mutex>
#include <random>
#include <utility>
#include <vector>
#include <thread>

using namespace std;

constexpr long long size= 1000000;   
mutex myMutex;

void sumUp(unsigned long long& sum, const vector<int>& val, 
   unsigned long long beg, unsigned long long end){
   long long localSum = 0;
    for (auto it= beg; it < end; ++it){
        localSum+= val[it];
    }
    lock_guard<mutex> myLock(myMutex);
    sum += localSum;
}

int main(){

  cout << endl;

  vector<int> randValues;
  randValues.reserve(size);

  mt19937 engine (0);
  uniform_int_distribution<> uniformDist(1,10);
  for ( long long i=0 ; i< size ; ++i)
     randValues.push_back(uniformDist(engine));
 
  unsigned long long sum= 0;
  auto start = chrono::system_clock::now();

  int threads = 4;
  thread t[threads];
  long long slice = size / threads;
  int startIdx=0;
  for (int i = 0; i < threads; ++i) {
    cout << "Thread[" << i << "] - slice ["
         << startIdx << ":" << startIdx+slice-1 << "]" << endl;
    t[i] = thread(sumUp, ref(sum), ref(randValues), startIdx, startIdx+slice-1);
    startIdx += slice;
  }

  for (int i = 0; i < threads; ++i)
     t[i].join();

  chrono::duration<double> dur= chrono::system_clock::now() - start;
  cout << "Time for addition " << dur.count() << " seconds" << endl;
  cout << "Result: " << sum << endl;

  cout << endl;

}

Solutions

Expert Solution

Modified code for sum_thread.cpp

#include <chrono>
#include <iostream>
#include <mutex>
#include <random>
#include <utility>
#include <vector>
#include <thread>

using namespace std;

//constexpr long long size = 1000000;
mutex myMutex;

void sumUp(unsigned long long& sum, const vector<int>& val,
   unsigned long long beg, unsigned long long end) {
   long long localSum = 0;
   for (auto it = beg; it < end; ++it) {
       if(val[it])
       {
           //local sum is sum of all elements of vectors that are allocated to this thread
           localSum += 1/val[it];
       }
   }
   lock_guard<mutex> myLock(myMutex);
   sum += localSum;
}

int main() {

   cout << endl;

   //long long size = 1000000;
   //here we are setting the n as 20
   long long size = 20;

   vector<int> randValues;
   randValues.reserve(size);

   mt19937 engine(0);
   uniform_int_distribution<> uniformDist(1, 10);
   for (long long i = 0; i< size; ++i)
       randValues.push_back(uniformDist(engine));

   unsigned long long sum = 0;
   auto start = chrono::system_clock::now();

   int threads = 4;
   //thread t[threads];
   thread t[4];
   long long slice = size / threads;
   int startIdx = 0;
   for (int i = 0; i < threads; ++i) {
       cout << "Thread[" << i << "] - slice ["
           << startIdx << ":" << startIdx + slice - 1 << "]" << endl;
       t[i] = thread(sumUp, ref(sum), ref(randValues), startIdx, startIdx + slice - 1);
       startIdx += slice;
   }

   for (int i = 0; i < threads; ++i)
       t[i].join();

   chrono::duration<double> dur = chrono::system_clock::now() - start;
   cout << "Time for addition " << dur.count() << " seconds" << endl;
   cout << "Result: " << sum << endl;

   cout << endl;

}

Output screenshot


Related Solutions

MATLAB question! 4. (a) Modify the code, to compute and plot the quantity E = 1/2mv^2...
MATLAB question! 4. (a) Modify the code, to compute and plot the quantity E = 1/2mv^2 + 1/2ky^2 as a function of time. What do you observe? Is the energy conserved in this case? (b) Show analytically that dE/dt < 0 for c > 0 while dE/dt > 0 for c < 0. (c) Modify the code to plot v vs y (phase plot). Comment on the behavior of the curve in the context of the motion of the spring....
-Write a program in C++: • to find the sum of the series 1! /1+2! /2+3!...
-Write a program in C++: • to find the sum of the series 1! /1+2! /2+3! /3+4! /4+5! /5 using the function1, • to convert decimal number to binary number using the function2, • to check whether a number is a prime number or not using the function3, • to check whether two given strings are an anagram using the function4. important must do in (Multi-Filing) of c++
a_list = [1, 2, 3, 4, 5] list_index = 7 #----------------------------------------------------------- #You may modify the lines...
a_list = [1, 2, 3, 4, 5] list_index = 7 #----------------------------------------------------------- #You may modify the lines of code above, but don't move them! #When you Submit your code, we'll change these lines to #assign different values to the variables. #In this problem, we're going to use some unfamiliar syntax. #You'll learn more about this syntax in Unit 4. For now, #though, you don't need to understand the syntax. All you #need to know is that right now, this code will...
It is desired to compute the sum of the first 10 terms of the series 14k3 = 20k2 + 5k, k = 1, 2, 3, …
It is desired to compute the sum of the first 10 terms of the series14k3 = 20k2 + 5k, k = 1, 2, 3, … a. Develop a pseudocode description of the required program.b. Write and run the program described in part a.
IN C++ Modify the above program to compute the side area, total area, and volume of...
IN C++ Modify the above program to compute the side area, total area, and volume of a cylinder and the area and volume of a sphere, depending on the choice that the user makes. Your program should ask users to enter 1 to choose cylinder or 2 for sphere, and display an "invalid choice error" for other values. For a cylinder, we want to compute: Side area: (2*PI*r) * h Total Area: 2*(PI*r2) + Side area Volume: (PI*r2)*h For a...
[PYTHON] Modify the examaverages.py program included with this assignment so it will also compute the overall...
[PYTHON] Modify the examaverages.py program included with this assignment so it will also compute the overall average test grade. E.g if there are 3 test each student must take and the user enters the following set of test scores for the two students…: 30, 40, 50 for the first student 50, 60, 70 for the second student …then program will print the average for each student (i.e. 40 for the first student and 60 for the second student – the...
Modify the code below to implement the program that will sum up 1000 numbers using 5...
Modify the code below to implement the program that will sum up 1000 numbers using 5 threads. 1st thread will sum up numbers from 1-200 2nd thread will sum up numbers from 201 - 400 ... 5th thread will sum up numbers from 801 - 1000 Make main thread wait for other threads to finish execution and sum up all the results. Display the total to the user. #include <pthread.h> #include <stdio.h> #include <stdlib.h> #define N_OF_THREADS 4 void * print(void...
SE-FamilySize 1 1 4 3 2 4 2 3 4 2 4 1 4 2 2...
SE-FamilySize 1 1 4 3 2 4 2 3 4 2 4 1 4 2 2 4 5 4 5 4 4 2 4 3 1 2 3 5 5 5 Make a confidence interval. Be sure you show all the steps you took. Include a screen shot of any applet you used in your calculations. 2. Choose a confidence level (1 – α). 3. What is xbar? 4. What is s? 5. What is t? (Show a screen shot...
"4. (Modify) Modify Program 7.14 so that the user inputs the initial set of numbers when...
"4. (Modify) Modify Program 7.14 so that the user inputs the initial set of numbers when the program runs. Have the program request the number of initial numbers to be entered." //C++ Program 7.14 as follows #include #include #include #include using namespace std; int main() { const int NUMELS = 4; int n[] = {136, 122, 109, 146}; int i; vector partnums(n, n + NUMELS); cout << "\nThe vector initially has the size of " << int(partnums.size()) << ",\n and...
Modify the program 5-13 from page 279 such that will also compute the class average. This...
Modify the program 5-13 from page 279 such that will also compute the class average. This class average is in addition to each individual student score average. To accomplish this additional requirement, you should do the following: 1. Add two more variables of type double: one for accumulating student averages, and one to hold the class average. Don't forget, accumulator variable should be initialized to 0.0. 2. Immediately after computing individual student average, add a statement that will accumulate the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT