创建新线程时在lambda内部使用unique_ptr的线程安全性
Thread-safety of using unique_ptr inside lambda when creating new thread
我想知道下面的代码是否线程安全
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。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 线程之间的布尔停止信号
- 为什么std::async使用同一个线程运行函数
- 用于矢量处理的多个线程
- C++为线程工作动态地分割例程
- std::shared_ptr::unique(),复制和线程安全