I wrote a C++ class which can take a vector of functions and their respective arguments and execute them in parallel and return a vector of results from its respective functions.
// @file: mthread.hh
// @author: Tushar Chaurasia (Dark-CodeX)
// @license: This file is licensed under the GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007. You may obtain a copy of this license at https://www.gnu.org/licenses/gpl-3.0.en.html.
#ifndef MTHREAD_HH
#define MTHREAD_HH
#include <vector>
#include <thread>
#include <functional>
namespace openutils
{
template <typename return_type, typename... args>
class mthread
{
private:
std::vector<return_type> ret_val;
std::vector<std::thread> threads;
public:
void execute_processes(const std::vector<std::function<return_type(args...)>> &functions, const std::vector<args> &...a);
const std::vector<return_type> &get() const;
std::vector<return_type> &get();
};
template <typename return_type, typename... args>
void mthread<return_type, args...>::execute_processes(const std::vector<std::function<return_type(args...)>> &functions, const std::vector<args> &...a)
{
std::vector<return_type> temp_val(functions.size()); // pre allocate
this->threads = std::vector<std::thread>(functions.size()); // pre allocate
for (std::size_t i = 0; i < functions.size(); i++)
{
this->threads[i] = std::thread([i, &temp_val, &functions, &a...]()
{ temp_val[i] = (functions[i](a[i]...)); });
}
for (std::size_t i = 0; i < this->threads.size(); i++)
{
this->threads[i].join();
}
this->ret_val.swap(temp_val);
}
template <typename return_type, typename... args>
const std::vector<return_type> &mthread<return_type, args...>::get() const
{
return this->ret_val;
}
template <typename return_type, typename... args>
std::vector<return_type> &mthread<return_type, args...>::get()
{
return this->ret_val;
}
}
#endif
The above library can be used as:
int main()
{
openutils::mthread<int, std::pair<int, int>> thread;
std::vector<std::pair<int, int>> args({{10, 20}, {5, 5}});
thread.execute_processes({[](std::pair<int, int> x)
{ return x.first + x.second; },
[](std::pair<int, int> x)
{ return x.first - x.second; }},
args);
std::vector<int> get = thread.get();
for (const int &x : get)
printf("%d\n", x);
return 0;
}
Result:
30
0
Any suggestions, improvements are appreciated.