cyrax
cyrax

Reputation: 13

Container Thread Safety

I'm aware of Container Thread Safety topic listed there: https://en.cppreference.com/w/cpp/container

But I want to know: can I use non-const member functions and const member functions concurrently without blocking (a mutex)? More specific:

  1. Can I use std::vector::push_back and std::vector::size concurrently?
  2. Can I use std::set::insert and std::set::size concurrently?

This doesn't make a practical sense commonly, but I don't need an exact result of size which I'll use, I just need a valid result at the time when I call it.

P.S. My doubts are come from there: https://www.cplusplus.com/reference/set/set/insert/ where they say for std::set::insert that

Concurrently accessing existing elements is safe

So maybe getting the size of containter is also safe.

Upvotes: 1

Views: 840

Answers (1)

TonySalimi
TonySalimi

Reputation: 8447

The main thread-safety rule of stl containers is that if more than one working thread is accessing a shared container, and at least one of them is non-const, then the threads should be synchronized. If you do not put any synchronizations, it will be undefined behavior.

if you take a look at the C++ reference here for std::vector::size(), it says:

Data Races

The container is accessed. No contained elements are accessed: concurrently accessing or modifying them is safe.

As mentioned, the vector container will be accessed during the call to .size() and this access does not allow you to call non-const methods at the same time on the vector. If you push_back an element into the vector when you get the size of the vector by calling .size(), then the behavior of your program will be undefined.

Upvotes: 1

Related Questions