std::线程传递向量元素(按引用)
std::thread pass vector element by reference
我试图弄清楚为什么以下工作:
threaded thr[8] = { threaded(), threaded() ,threaded() ,threaded() ,threaded() ,threaded() ,threaded() ,threaded() };
std::vector<std::thread> vec;
for (int i = 0; i < threads; i++)
{
vec.push_back(std::thread(&threaded::calc, &thr[i], i, num_samples));
}
而以下则没有:
std::vector<threaded> thr;
std::vector<std::thread> vec;
for (int i = 0; i < threads; i++)
{
thr.push_back(threaded());
vec.push_back(std::thread(&threaded::calc, &thr[i], i, num_samples));
}
我尝试使用 std::ref 而不是 &- 它仍然不起作用。以下是线程的定义:
struct threaded
{
float elapsed1 = 0;
float elapsed2 = 0;
float res = 0;
float res_jit = 0;
void calc(int thread, int num_samples){//do something}
};
通过不起作用,我的意思是,当使用矢量和 &,我遇到内存访问冲突,当我尝试使用 std::ref(thr[i]) 而不是 &,它不想编译以下错误:
Error C2672 'std::invoke': no matching overloaded function found
和
Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'
如果我只使用 thr[i],它可以正常工作,但我想修改线程类的值,所以我真的不想传递副本。
随着向量thr
随着每次push_back
调用而变大,最终超过保留内存区域的容量,它需要重新分配其存储并将其元素复制(或移动)到新分配的空间。一旦发生这种情况,对象开始存在于新的内存地址下,因此先前获得的地址将失效。为了防止搬迁,请在进入环路之前预留足够的空间:
std::vector<threaded> thr;
thr.reserve(threads);
或者默认一次构造所有元素:
std::vector<threaded> thr(threads);
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 设计将引用元素移动到开头的数据结构.C++
- 为什么通过 vector<reference_wrapper> 的元素删除引用的值<T>不会使向量无效?
- 将新元素添加到列表中,并返回对该元素的引用?
- 如何告诉自动推断向量<bool>元素的非引用类型
- 通过引用访问矢量元素是否会降低C++的空间复杂性?
- 通过引用传递时访问std::vector的元素
- 如何取消引用和打印指针数组的每个元素?
- 如何从模板获取常量矢量元素的引用
- 调整大小后保持对矢量元素的引用有效
- 取消引用C++中的指针元素
- 在这种情况下,如何返回对数组中元素的引用?
- C++ - 返回对矢量元素的引用
- 引用保留向量中的第一个元素
- C++ 当容器在使用前被破坏/修改时发出警告(通过引用元素或迭代器使用)
- 如何通过引用对用户定义对象的类型集 (STL) 的数组元素进行增强迭代?
- 如何理解取消引用指向数组的指针会获取指向元素的指针
- 如何将一个向量的元素引用复制到另一个向量?
- 通过[]运算符返回矢量元素引用