【问题标题】:Implementing a parallel_for_each function实现 parallel_for_each 函数
【发布时间】:2013-11-22 10:22:10
【问题描述】:

我认为,我当前的尝试无法编译是因为std::bind 无法推断返回类型的问题。实际的错误信息是

1>Source.cpp(24):错误 C2783: 'enable_if::value,std::_BindRx(_fastcall _Farg0::* )(_Ftypes...) volatile const,_Rx,_Farg0,_Ftypes...>,_Types...>>::type std::bind(Rx (_fastcall _Farg0::* const )(_Ftypes...) volatile const,_Types &&...)' : 无法推断出 '_Ret' 的模板参数

另外,我应该通过值还是引用将函数传递给 std::bind? (通过 std::ref)。

template<class InputIt, class Function>
void parallel_for_each(InputIt first, const size_t elements, Function &function)
{
    unsigned int max_threads = std::max(1u, std::min(static_cast<unsigned int>(elements), std::thread::hardware_concurrency()));
    std::vector<std::thread> threads;
    threads.reserve(max_threads);
    size_t inc = elements / max_threads;
    size_t rem = elements % max_threads;
    std::cout << "inc = " << inc << '\n';
    auto last = first + elements;
    for (; first != last; first += rem > 0 ? inc + 1, --rem : inc)
    {
        std::cout << "rem = " << rem << '\n';
        std::cout << "first = " << *first << '\n';
        threads.emplace_back(std::bind(std::for_each, first, first + inc, function));
    }
    for (auto &t: threads) 
        t.join();
}

调用它:

std::vector<int> numbers(678, 42);
parallel_for_each(begin(numbers), numbers.size(), [](int &x){ ++x; });
for (auto &n : numbers)
    assert(n == 43);
std::cout << "Assertion tests passed\n";

编辑:我将错误的 for 循环替换为:

while (first != last)
{
    auto it = first;
    first += rem > 0 ? --rem, inc + 1 : inc;
    threads.emplace_back(std::bind(std::for_each<InputIt, Function>, it, first, function));
}

【问题讨论】:

  • 好主意。考虑使用 OpenMP。
  • FWIW,C++17 引入for_each(execution::par, ...)

标签: c++ multithreading templates c++11


【解决方案1】:

你可以手动点,你要用什么模板

threads.emplace_back
(
   std::bind(std::for_each<InputIt, Function>, first, first + inc, function)
);

或者,您可以简单地使用 lambda,而不使用 std::bind

【讨论】:

    【解决方案2】:

    是的,你是对的,std::for_each 是一个函数模板,所以你需要明确地选择一个特化。另外,你实际上不需要std::bind,线程构造函数(emplace)支持相同的语法。

    关于您的第二个问题,您应该通过引用传递值,因为您需要显式复制值以防例如:仿函数将具有内部状态!

    您的实现中还有一些其他问题。

    你不应该通过引用来获取函数,因为这会阻碍传递 lambdas/functors。此外,您应该使用std::async 而不是使用普通的std::thread,这将为您提供异常安全性。如果在您的实现中,仿函数会引发异常,则将调用 std::terminate

    与多线程没有直接关系的另一件事是我收到了来自 clang 的警告:

    警告:逗号运算符的左操作数无效[-Wunused-value] for (; first != last; first += rem > 0 ? inc + 1, --rem : inc)

    这可能是我得到段错误的原因。

    在未来的版本中,您可以添加负载平衡之类的功能。

    【讨论】:

    • 感谢您的提示。是的,OP 中的代码甚至无法正常工作,但我正在努力。
    • @A.B.啊,是的,我也刚发现。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2010-12-13
    相关资源
    最近更新 更多