gpt4 book ai didi

c++ - 实现 parallel_for_each 函数

转载 作者:太空狗 更新时间:2023-10-29 20:41:52 27 4
gpt4 key购买 nike

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

1>Source.cpp(24): error 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 &&...)' : could not deduce template argument for '_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));
}

最佳答案

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

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

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

关于c++ - 实现 parallel_for_each 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20142449/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com