97int parallelize(
const Function_ fun,
const Index_ tasks,
int threads) {
102 if (threads <= 1 || tasks == 1) {
107 Index_ tasks_per_worker = tasks / threads;
108 int remainder = tasks % threads;
109 if (tasks_per_worker == 0) {
110 tasks_per_worker = 1;
116 mexec.initialize(threads,
"failed to execute R command");
118 std::vector<std::thread> runners;
119 sanisizer::reserve(runners, threads);
120 auto errors = sanisizer::create<std::vector<std::exception_ptr> >(threads);
123 for (
int w = 0; w < threads; ++w) {
124 Index_ length = tasks_per_worker + (w < remainder);
126 runners.emplace_back(
127 [&](
const int id,
const Index_ s,
const Index_ l) ->
void {
131 errors[id] = std::current_exception();
133 mexec.finish_thread();
144 for (
auto& x : runners) {
148 for (
const auto& err : errors) {
150 std::rethrow_exception(err);