Roh*_*are 2 c++ future shared-ptr c++11
我正在将我的代码转换为多线程到性能增强.
我有shared_ptr的向量和另一个类的对象,我从vector向量传递shared_ptr,并将对象作为参数传递给函数.我使用std :: async调用它,但它给了我以下错误:
line from where I am making async call : required from here
/usr/include/c++/4.8.2/functional1697.61: error: no type named 'type'
in 'class std::result_of<void (*(std::shared_ptr<A>, B))
(const std::shared_ptr<A>&, B&)>'typedef typename
result_of<_Callable(_Args...)>::type result_type;
Run Code Online (Sandbox Code Playgroud)
这是代码片段:
void foo(std::vector<std::shared_ptr<A>>& a, B b){
std::vector<std::future<void>> tasks;
for(auto& sptr : a ){
tasks.push_back(std::async(std::launch::async, foo1, a, b))
}
void foo1(const std::shared_ptr<A>& a, B& b ){
//do some stuff
}
Run Code Online (Sandbox Code Playgroud)
你能帮我么.谢谢
我正在将我的代码转换为多线程到性能增强.
我们走了......我预测会遇到困难.
该错误告诉您foo1使用std::async将传递给它的参数调用的结果未定义,即您无法使用这些参数调用该函数.
原因是该函数foo1采用类型的参数B&但std::async复制其参数并将副本转发到目标函数,因此它将复制b然后调用foo1该副本作为右值转发,该值不能绑定到左值引用类型B&.
如果你真的想b通过引用传递,那么你需要包装它:
std::async(std::launch::async, foo1, a, std::ref(b))
Run Code Online (Sandbox Code Playgroud)
但是你应该小心,看起来每个线程都会对同一个B对象进行非const引用,这意味着它们可能会同时修改该对象,这将导致数据争用(和未定义的行为),除非B已经是线程 -安全或您修改功能foo1以同步访问B.
如果代码在多个线程中使用是不安全的,那么只需在代码上撒上多线程的小精灵灰尘就不会让它变得更快.