Home > Enterprise >  Are dedicated std::vectors on the heap threadsafe?
Are dedicated std::vectors on the heap threadsafe?

Time:03-26

This should be a simple question, but I'm having difficulty finding the answer.

If I have multiple std::vectors on the heap which are only accessed by one thread each are they thread-safe? That is, because the vectors will be dedicated to a particular thread, I am only concerned about memory access violations when the vectors resize themselves, not about concurrent accesses, data races, etc.

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.

Thanks!

CodePudding user response:

Access to different objects is thread-safe, new used by std::vector's allocator is of course thread-safe too.

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.

I think you misunderstand how vector works. The object itself contains just a few pointers, that's it. The memory is allocated from the dynamic storage(heap) almost always. Unless you override it with your own allocator and use alloca or similar dangerous stuff.

So if you do

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

The memory for the three pointers inside local_variable will be on stack but 1,2,3,4 objects are on the heap.

  • Related