为什么标准::异步复制其常量和放大器;参数呢? [英] Why does std::async copy its const & arguments?

查看:96
本文介绍了为什么标准::异步复制其常量和放大器;参数呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图加快使用的std ::异步的程序。比方说,我有一个函数

I'm trying to speed up a program by using std::async. Let's say I have a function

T* f (const T& t1, const T& t2, const T& t3)

其中,T是一类是复制昂贵。我有f相不同的参数几个独立的电话,我尝试用STD并行他们::异步大致是这样的:(其中m_futures是正确类型的期货一个std ::向量)

Where T is a type that is expensive to copy. I have several independent calls of f with different arguments and I try to parallelize them with std::async approximately like this: (where m_futures is a std::vector of futures of the correct type).

for (...) {
   m_futures.push_back (
       std::async(
           std::launch::async,
           f,
           a,b,c));
}

我观察到上述code减慢我的程序的执行。我通过它加强使用gdb并创建未来的时候,T的拷贝构造函数被调用三次。这是为什么?这些参数的a,b,c的堆中分配,但也许编译器不认识呢?我能获得某种明确的?

I observed that the above code slows down the execution of my program. I stepped through it with gdb and when the future is created, the copy constructor of T is called three times. Why is that? The arguments a,b,c are heap allocated, but maybe the compiler does not know about it? Can I make it explicit somehow?

时它总是异步创建的参数的拷贝,即使他们应当由const引用传递是STD中的情况::?我能以某种方式避免这种情况?在我幼稚的心灵,应该只是各地传递给函数的不同调用的指针(只从内存读取反正)我在Linux上使用GCC-4.6.3如果该事项。

Is it always the case that std::async creates copies of the arguments, even if they should be passed by const reference? Can I avoid this somehow? In my naive mind, there should just be a pointer passed around to the different invocations of the function (which only reads from the memory anyway.) I'm using gcc-4.6.3 on Linux if that matters.

推荐答案

这不会是安全的,只存储引用,因为没有什么可以保证没有数据比赛(和更深入,单纯的存在的对象,如@utapistim在她伤心地删除了帖子说)。

It wouldn't be safe to store references only, since there's nothing to guarantee the absence of data races (and more profoundly, the mere existence of objects, as @utapistim said in her sadly deleted post).

如果你真的想一个参考,而不是副本,的'再愿意赌这个是正确的生活,那么你可以简单地使用一个参考包装:

If you actually want a reference rather than a copy, and you're willing to bet your life on this being correct, then you can simply use a reference wrapper:

std::async(std::launch::async, f, std::cref(a), std::cref(b), std::cref(c))

这篇关于为什么标准::异步复制其常量和放大器;参数呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆