template<typename FuncVec> int handle(const vector<int>& v, FuncVec f, int MAX_THREAD) { vector<future<int>> threads; std::vector<int> answers; int mid = v.size() / MAX_THREAD; int start = 0, end = start + mid; for (int i = 0; i < MAX_THREAD; ++i) { start = mid * i; end = start + mid; if (end != (int) v.size() && (int) v.size() - end < mid) end = v.size(); threads.emplace_back (std::async(std::launch::async, f, v, start, end)); } for (auto& thread : threads) { answers.push_back(thread.get()); } return f(answers, 0, answers.size()); } 

Actually, you need to speed up this function. Now on 4 streams issue such indicators:

We create 10000211 elements. (Single stream) Amount = 45012639 Time = 171.846ms. (Multithread) Amount = 45012639 Time = 193.831ms.

What are some ideas?

We found out that for some reason, only one core works. Full code here

  • one
    Are you sure that by calling async in this way, you are creating a new thread? How about threads.emplace_back (std :: launch :: async, async (f, v, start, end)); - gbg
  • one
    For a long time, do not suffer, and run single-threaded. For such a small task there is no point in multithreading. The overhead of starting a stream is greater than the gain. - Harry
  • one
    @Harry - how do you know what function the author calls? This is a piece of generalized code. - gbg
  • one
    @gbg Judging by the given results by time, and by the word "sum" :) - Harry
  • 2
    Perhaps the question must be formulated differently. Somehow in the form: and when in the computational problem is it necessary to use multithreading? With a simple summation of the elements of a vector (or searching for something among them) you have a situation where everything depends on the performance of the memory (cache). What for one thread, what for several. Functional devices in the CPU (namely, their use and can actually separate threads) are not provided with data (idle). I do not know what you were driving, I have your program shows for the amount of 1.35428ms. (one) / 12.3607ms (2 threads) - avp

0