C++ 为每个函数实现并行_
我认为,由于C++ 为每个函数实现并行_,c++,multithreading,templates,c++11,C++,Multithreading,Templates,C++11,我认为,由于std::bind无法推断返回类型的问题,我当前的尝试无法编译。实际的错误消息是 1> Source.cpp(24):错误C2783: 'enable_if::value,std:_BindRx(_fastcall _Farg0::*)(\u Ftypes…)volatile const,\u Rx,\u Farg0,\u Ftypes…>,\u Types…>>::type std::bind(Rx) (\u Farg0::*const)(\u Ftypes…)volatile c
std::bind
无法推断返回类型的问题,我当前的尝试无法编译。实际的错误消息是
1> Source.cpp(24):错误C2783:
'enable_if::value,std:_BindRx(_fastcall
_Farg0::*)(\u Ftypes…)volatile const,\u Rx,\u Farg0,\u Ftypes…>,\u Types…>>::type std::bind(Rx)
(\u Farg0::*const)(\u Ftypes…)volatile const,\u Types
&&“…)”:无法推断“\u Ret”的模板参数
另外,我应该通过值还是引用将函数传递给std::bind吗?(通过std::ref)
模板
每个元素的无效并行元素(输入优先、常量大小元素、函数和函数)
{
unsigned int max_threads=std::max(1u,std::min(静态转换(元素),std::thread::hardware_concurrency());
向量线程;
线程保留(最大线程数);
尺寸=元件/最大螺纹;
尺寸\u t rem=元件%max\u螺纹;
std::cout您可以手动指出要使用的模板
threads.emplace_back
(
std::bind(std::for_each<InputIt, Function>, first, first + inc, function)
);
threads.emplace\u back
(
std::bind(std::for_each,first,first+inc,function)
);
或者,您可以简单地使用lambda,而不使用std::bind是的,您是正确的,std::for_每个
都是一个函数模板,因此您需要显式地选择一个专门化。此外,您实际上不需要std::bind
,线程构造函数(emplace)支持相同的语法
关于第二个问题,您不应该通过引用传递值,因为您需要显式复制值,以防出现以下情况:函子将具有内部状态
您的实现中还存在一些其他问题
您不应该通过引用获取函数,因为这将妨碍lambda/functor的正确传递。此外,您应该使用std::thread
而不是普通的std::async
,这将为您提供异常安全性。如果在您的实现中functor会引发异常,则会调用std::terminate
另一件与多线程没有直接关系的事情是,我从clang那里得到了以下警告:
警告:逗号运算符的左操作数无效[-Wunused value]
对于(;first!=last;first+=rem>0?inc+1,--rem:inc)
这可能是我遇到seg故障的原因
在将来的版本中,你可以添加一些类似负载平衡的东西。
好主意。考虑使用OpenMP.FWW,C++ 17介绍<代码> FoYE(执行::Par,…)<代码>。谢谢提示。是的,OP中的代码甚至不能正常工作,但我正在努力。“A.B. Ah yeah,我也发现了。”
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";
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)
);