堆上的专用 std::vectors 线程安全吗?

Are dedicated std::vectors on the heap threadsafe?

这应该是一个简单的问题,但我很难找到答案。

如果我在堆上有多个 std::vectors,每个 一个线程访问它们 它们是线程安全的吗?也就是说,因为向量将专用于特定线程,所以我只关心向量调整自身大小时的内存访问冲突,而不关心并发访问、数据竞争等。

当然,我可以将每个向量放在其线程的堆栈上,但它们会非常大,可能会导致我的应用程序出现堆栈溢出。

谢谢!

访问不同的对象是thread-safe,std::vector的分配器使用的new当然也是thread-safe。

Of course I could just stick each vector on its thread's stack, but they will be very large and could cause a stack overflow in my application.

我认为您误解了 vector 的工作原理。对象本身只包含几个指针,仅此而已。内存几乎总是从动态存储(堆)中分配的。除非你用自己的分配器覆盖它并使用 alloca 或类似的危险东西。

所以如果你这样做

std::vector<int> local_variable{1,2,3,4};

local_variable 中的三个指针的内存将在堆栈上,但 1,2,3,4 对象在堆上。