greensky00 / skiplist

Generic lock-free Skiplist container pure C implementation, STL-style set, map
MIT License
142 stars 20 forks source link

map erase error #1

Open ggkingdom opened 6 years ago

ggkingdom commented 6 years ago

hello, when I use sl_map :: erase(key) , program stop in skiplist_wait_for_free how to resolve?

greensky00 commented 6 years ago

Hi @ggkingdom , sorry for the late reply.

sl_map::erase(...) (skiplist_wait_for_free() especially) waits for all the other threads holding the same key-value pair until they release it, to guarantee thread safety.

If a single thread that is holding an iterator tries to erase it by key, it will be hanging there. Below is a simple example of it:

sl_map<int, int> sl;
...
auto ii = sl.begin(); // now `ii` is holding a key-value pair.
// Below command will wait until there is no reference to `ii->first`, 
// but this thread is holding it by `ii`. Hence it will be hanging here forever.
sl.erase(ii->first); 

To avoid such case, there are two options:

1) Release iterator before erasing by key

auto ii = sl.begin();
int key = ii->first;
ii++; // Iterator moved, now no one refers `key`.
sl.erase(key); 

2) Erase by iterator

auto ii = sl.begin();
ii = sl.erase(ii); // Will return the iterator of next key-value.

Maybe I need to make another version of map wrapper that is using lazy garbage collection instead of busy waiting.

Thanks.