My need is just like below: One thread (named thread 1)just keeps inserting pairs into the common map. And the other thread (named thread 2)keeps getting the element at the begin position(no matter if it is still the begin while other thread insert an element at the begin position) and do some operation to the element and erase the iterator.
I know that STL is not threadsafe, but it is still a good container to use. So my method is every time thread 2 get the element, I make a copy of it and do my work, and protect insert/delete/begin/end by one mutex.
pseudocode like below under c++17
my_map {
insert(){
lock_guard(mutex)
map.insert()
}
erase(){
lock_guard(mutex)
map.erase()
}
end(){
lock_guard(mutex)
map.end()
}
begin(){
lock_guard(mutex)
map.begin()
}}
thread 1:
while(1){
sleep(1)
my_map.insert()
}
thread 2:
while(1){
auto it = my_map.begin()
auto k = it->first;
auto v = it->second;
work(k, v);
my_map.erase(it);
}
My question is would my code be threadsafe? And will insert in thread 1 affects the actual value of k and v in thread 2?(again no matter if it is at the real begin position, I just want to get k and v of the iterator when thread 2 gets using "auto it = my_map.begin()")