c++ - 在异步调用中将 shared_ptr 作为参数传递

标签 c++ c++11 shared-ptr future

我正在将我的代码转换为多线程以提高性能。

我有 shared_ptr 的 vector 和另一个类的对象,我正在将 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;

这是代码片段:

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
 }

你能帮帮我吗?谢谢

最佳答案

I am converting my code to multi thread to performance enhancement.

我们开始......我预测困难。

错误是告诉你调用 foo1 的结果是 std::async 将传递给它的参数未定义,即你不能调用带有这些参数的函数。

原因是函数 foo1 接受类型为 B& 的参数,但是 std::async 复制它的参数并转发 copys 到目标函数,所以它将复制 b 然后调用 foo1 并将该拷贝作为右值转发,不能绑定(bind)到 an B& 类型的左值引用。

如果你真的想通过引用传递 b 那么你需要包装它:

std::async(std::launch::async, foo1, a, std::ref(b))

但是你应该小心,看起来每个线程都会有一个对同一个 B 对象的非 const 引用,这意味着它们可能正在同时修改该对象,这将导致数据竞争(和未定义的行为),除非 B 已经是线程安全的,或者您修改函数 foo1 以同步对 B 的访问。

如果代码在多线程中使用不安全,那么仅仅在您的代码上撒上多线程仙尘不会使它变得更快。

关于c++ - 在异步调用中将 shared_ptr 作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31595041/

相关文章:

c++ - 将 "this"对象的 shared_ptr 获取到另一个函数 : giving run time exception

c++ - boost::shared_ptr <> "explicit shared_ptr( Y * p ): px( p ), pn()//Y must be complete"

C++ toString() 和 sprintf()

c++ - 在这种情况下如何删除 vector 元素?

c++ - 如何输出计算到小数点后两位的整数?

c++ - NULL、0、nullptr 的解释

c++ - 在 C++ 中解析文本时标记文本,这是新手的考验

c++ - 在单字符数据类型中将空格作为输入?

C++ std::vector<int> 问题

c++ - 当 use_cout() == 1 时 shared_ptr 没有被销毁