创建新线程时在lambda内部使用unique_ptr的线程安全性

Thread-safety of using unique_ptr inside lambda when creating new thread

本文关键字:线程 unique 内部 ptr 安全性 lambda 新线程 创建      更新时间:2023-10-16

我想知道下面的代码是否线程安全

void use_value(int i, unique_ptr<vector<int>> v);
for (int i = 0; i < 10; i++){
    unique_ptr<vector<int>> ptr = make_unique<vector<int>>(10);
    // ...
    // Here, the vector pointed to by ptr will be filled with specific values for each thread.
    // ....
    thread(
        [i, &ptr](){
            use_value(i, move(ptr));
        }
    );
}

谢谢

这是未定义的行为。您不知道何时调用lambda主体。因此,您通过引用捕获的ptr很可能在那时超出了作用域,资源被破坏,您只剩下一个悬空引用。

你应该"移动捕获"ptr(或者更好,只是vector)到lambda中,如果你可以访问c++14。

如果你移动(或复制)向量,你的代码将是线程安全的。