I wonder if this situation is (thread-)safe or not.
There is a thread that only pushes to a std::queue.
And there is another thread that only pops from the std::queue.
Since whether the queue is empty or not, is managed thread-safely, the later thread won't fail popping.
Could you help me, please?
Thank you.
I believe the answer is no.
The standard says (§23.2.2/1):
For purposes of avoiding data races (17.6.5.9), implementations shall consider the following functions to be const: begin, end, rbegin, rend, front, back, data, find, lower_bound, upper_bound, equal_range, at and, except in associative or unordered associative containers, operator[].
At least as I'd interpret things (and Herb Sutter seems to agree) that means those functions (and only those functions) can be treated as "thread safe". Push and pop aren't on the list, so you can't assume they're thread safe.
I'd also add that even popping will actually write data -- when you pop an item from the container, the size of the container needs to be updated, so both pushing and popping do writing. When more than one thread does writing, you need to do something to ensure only one thread does it at a time.
To summarize: sorry, but no.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With