Fixed thread pool collecting results and errors
C++
#include <atomic>
#include <exception>
#include <functional>
#include <string>
#include <thread>
#include <vector>
struct Results { std::vector<int> values; std::vector<std::string> errors; };
Results runPool(const std::vector<std::function<int()>>& tasks, int workers) {
Results out{std::vector<int>(tasks.size()), std::vector<std::string>(tasks.size())};
std::atomic<std::size_t> next{0};
auto worker = [&] {
for (std::size_t i = next++; i < tasks.size(); i = next++)
try { out.values[i] = tasks[i](); }
catch (const std::exception& e) { out.errors[i] = e.what(); }
};
std::vector<std::thread> pool;
for (int i = 0; i < workers; ++i) pool.emplace_back(worker);
for (auto& t : pool) t.join();
return out;
}