Could I let one thread hold a reference (or iterator) to the first element of a std::deque while another is adding/removing elements at the back, but never touching the first element?
I know I can use a mutex to lock the entire data structure, but I was wondering since adding/removing elements at the back never invalidate iterators at the front (assuming back != front) if doing this could work.
EDIT
Here's an example that shows a race condition (the assertion fails) with clang-15 on a mac os. Interestingly, the same example but where insertions/removals are done at the back and the element is read at the front seems to work.
#include <deque>
#include <thread>
#include <cassert>
#include <chrono>
int main()
{
std::deque<int> deque;
deque.push_back(42);
auto thread1 = std::thread([&](){
for (auto i = 0u; i < 1000000000; ++i)
{
auto& j = deque.back();
using namespace std::chrono_literals;
std::this_thread::sleep_for(10ms);
assert(j == deque.back());
}
});
auto thread2 = std::thread([&](){
for (auto i = 0u; i < 1000000000; ++i)
if (deque.size() == 1)
deque.push_front(43);
else
deque.pop_front();
});
thread1.join();
thread2.join();
}