Skip to content

Instantly share code, notes, and snippets.

@rajkumar-p
Created March 11, 2020 19:01
Show Gist options
  • Save rajkumar-p/0dd8a81e3b7bdf3ab10ab17629ad977e to your computer and use it in GitHub Desktop.
Save rajkumar-p/0dd8a81e3b7bdf3ab10ab17629ad977e to your computer and use it in GitHub Desktop.
add() using a fine-grained strategy
template<typename T>
bool SortedList<T>::add(T elem)
{
NodeListWithLock<T> *prev = this->_head;
prev->lock_node();
NodeListWithLock<T> *curr = prev->_next;
while(curr != nullptr &&
curr->data() < elem) {
curr->lock_node();
prev->unlock_node();
prev = curr;
curr = curr->_next;
}
NodeListWithLock<T> *new_node =
new NodeListWithLock<T>(elem);
if (curr == nullptr) {
prev->_next = new_node;
prev->unlock_node();
} else {
curr->lock_node();
prev->_next = new_node;
new_node->_next = curr;
prev->unlock_node();
curr->unlock_node();
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment