并行调用std :: vector中的函数

时间:2017-10-20 21:39:56

标签: c++ c++14

我有std::vector std::function<void()>这样:

std::map<Event, std::vector<std::function<void()>>> observers_;

调用每个函数:

for (const auto& obs : observers_.at(event)) obs();

我想将其转换为并行for循环。由于我使用的是C++14,并且无法访问std::execution::parallel C++17,因此我找到了一个允许我创建ThreadPool的小库。

如何将for (const auto& obs : observers_.at(event)) obs();转换为并行调用observers_中每个函数的版本?我似乎无法使语法正确。我试过,但这不起作用。

std::vector<std::function<void()>> vec = observers_.at(event);
ThreadPool::ParallelFor(0, vec.size(), [&](int i)
{
    vec.at(i);
});

使用以下库的示例程序:

#include <iostream>
#include <mutex>

#include "ThreadPool.hpp"
////////////////////////////////////////////////////////////////////////////////

int main()
{
    std::mutex critical;
    ThreadPool::ParallelFor(0, 16, [&] (int i)
    {
        std::lock_guard<std::mutex> lock(critical);
        std::cout << i << std::endl;
    });
    return 0;
}

ThreadPool库。

#ifndef THREADPOOL_HPP_INCLUDED
#define THREADPOOL_HPP_INCLUDED

////////////////////////////////////////////////////////////////////////////////
#include <thread>
#include <vector>
#include <cmath>
////////////////////////////////////////////////////////////////////////////////

class ThreadPool {

public:

    template<typename Index, typename Callable>
    static void ParallelFor(Index start, Index end, Callable func) {
        // Estimate number of threads in the pool
        const static unsigned nb_threads_hint = std::thread::hardware_concurrency();
        const static unsigned nb_threads = (nb_threads_hint == 0u ? 8u : nb_threads_hint);

        // Size of a slice for the range functions
        Index n = end - start + 1;
        Index slice = (Index) std::round(n / static_cast<double> (nb_threads));
        slice = std::max(slice, Index(1));

        // [Helper] Inner loop
        auto launchRange = [&func] (int k1, int k2) {
            for (Index k = k1; k < k2; k++) {
                func(k);
            }
        };

        // Create pool and launch jobs
        std::vector<std::thread> pool;
        pool.reserve(nb_threads);
        Index i1 = start;
        Index i2 = std::min(start + slice, end);
        for (unsigned i = 0; i + 1 < nb_threads && i1 < end; ++i) {
            pool.emplace_back(launchRange, i1, i2);
            i1 = i2;
            i2 = std::min(i2 + slice, end);
        }
        if (i1 < end) {
            pool.emplace_back(launchRange, i1, end);
        }

        // Wait for jobs to finish
        for (std::thread &t : pool) {
            if (t.joinable()) {
                t.join();
            }
        }
    }

    // Serial version for easy comparison
    template<typename Index, typename Callable>
    static void SequentialFor(Index start, Index end, Callable func) {
        for (Index i = start; i < end; i++) {
            func(i);
        }
    }

};

#endif // THREADPOOL_HPP_INCLUDED

3 个答案:

答案 0 :(得分:3)

似乎你应该改变:

vec.at(i); // Only returns a reference to the element at index i

成:

vec.at(i)(); // The second () calls the function
--- OR ---
vec[i](); // Same

答案 1 :(得分:1)

提示:这是做什么的?

vec.at(i);

想要做什么?

无意义的是,当您的意思是at()时,您正在使用[]

答案 2 :(得分:-3)

这有效:

ThreadPool::ParallelFor(0, (int)vec.size(), [&] (int i)
{
    vec[i]();
});