【发布时间】: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