std::thread 通过引用传递向量元素

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

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] 它工作正常,但我想修改线程的值 class,所以我真的不想传递副本。

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

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

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

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