gpt4 book ai didi

c++ - std::thread 通过引用传递 vector 元素

转载 作者:行者123 更新时间:2023-11-28 02:05:59 25 4
gpt4 key购买 nike

我正在尝试弄清楚为什么以下方法有效:

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}
};

By 不起作用 我的意思是,当使用 vector 和 & 时,我遇到了内存访问冲突,当我尝试使用 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] 它工作正常,但我想修改线程类的值,所以我真的不想传递一个拷贝。

最佳答案

随着 vector thr 随着每次 push_back 调用而变大,最终超过保留内存区域的容量,它需要重新分配其存储空间并复制(或移动)它的元素到新分配的空间。一旦发生,对象开始在新的内存地址下生存,因此先前获得的地址将失效。为了防止重定位,在进入循环之前预留足够的空间:

std::vector<threaded> thr;
thr.reserve(threads);

或一次默认构造所有元素:

std::vector<threaded> thr(threads);

关于c++ - std::thread 通过引用传递 vector 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37509874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com