Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C++ std::queue safe if there are a pushing-only thread and a popping-only thread?

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.

like image 476
noname Avatar asked Jan 13 '23 22:01

noname


1 Answers

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.

like image 106
Jerry Coffin Avatar answered Jan 20 '23 13:01

Jerry Coffin