I'm writing an application which works with huge amounts of sequential data, and often found the need to use std::transform
. I see two potential improvements to std::transform
:
- Allow for variable number parameters.
- Take advantage of the linear separability of the data by multithreading.
Can anyone suggest any design/performance improvements on my implementation?
threaded_transform.h
#include <vector>
#include <thread>
template<typename InputIterator, typename OutputIterator,
typename Function, typename... Params>
OutputIterator
trans(InputIterator first, InputIterator last, OutputIterator result,
Function f, Params... params)
{
for (; first != last; ++first, ++result)
*result = f(*first, params...);
return result;
}
template<typename InputIterator, typename OutputIterator,
typename Function, typename... Params>
OutputIterator
threaded_transform(unsigned num_threads, InputIterator first,
InputIterator last, OutputIterator result,
Function f, Params... params)
{
std::size_t num_values = last - first;
std::size_t num_values_per_threads = num_values / num_threads;
std::vector<std::thread> threads;
threads.reserve(num_threads);
for (unsigned i = 1; i <= num_threads; ++i) {
if (i == num_threads) {
// The last thread processes the remaining values.
threads.push_back(std::thread(trans<InputIterator, OutputIterator, Function, Params...>,
first, last, result, f, params...));
} else {
threads.push_back(std::thread(trans<InputIterator, OutputIterator, Function, Params...>,
first, first + num_values_per_threads, result, f, params...));
}
first += num_values_per_threads;
result += num_values_per_threads;
}
for (auto& thread : threads)
thread.join();
return result;
}
main.cpp
#include <vector>
#include "threaded_transform.h"
int main()
{
auto sum = [] (int a, int b) { return a + b; };
std::vector<int> values = {1,2,3,4,5,6,7,8,9,10};
std::vector<int> results;
results.resize(10);
threaded_transform(4, values.cbegin(), values.cend(), results.begin(), sum, 10);
for (auto result : results) {
std::cout << result << std::endl;
}
}