In general, operations on the standard containers are not thread safe (mostly). The size
call on a std::vector
, for example, may fail when reallocations are happening.
Since a dequeue
does not reallocate or move the elements like a standard vector does, are there still conditions when calling size
on a dequeue can be unsafe? The most likely scenario seems to be when adding/removing elements in a different thread as the size
call is being made, but since accessing an integer is mostly safe, I'm having trouble thinking of how calling size
from a separate thread would be problematic.
std::dequeue::size() is NEVER thread safe. Because it's not required to be so in any standard.
The GCC implementation here https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/stl_deque.h is the result of a subtraction:
// [23.2.1.2] capacity
/** Returns the number of elements in the %deque. */
size_type
size() const _GLIBCXX_NOEXCEPT
{ return this->_M_impl._M_finish - this->_M_impl._M_start; }
Even if size were stored in a size_t
, or even an uint8_t
, and size()
were an inline function to return this variable, C++ makes no guarantees about the atomicity of different ints. Never assume something is threadsafe unless it is guaranteed to be so.