Suppose I have a sorted, singly-linked list of N integers containing no duplicates, and k threads (where k << N ), each trying to insert some integer (larger than the head node) into the list.
Is it possible to synchronize insertions into such a list such that:
?
First, if insertion into the collection is anything but a very infrequent task, then linked lists aren't a great solution for this - because finding the insertion point is an O(N)
operation, even for a sorted list, and hence going to end up scaling badly.
If you still need to do it, it's possible to perform insertion (unlike deletion) into a sorted list as lockless operation, with some care:
cur
cur
/ cur->next
) compare_and_swap(cur->next, new, new->next);
if (new->value == next->value) return; // someone beat us to it
if (new->value == next->value) return; // someone beat us to it
cur = cur->next
and repeat the dance (list is sorted, someone inserted before us) Ie the outcome of the attempt to link a new node in is either that we succeed, or that someone beat us to inserting the same node (in which case we're ok - it's already there), or someone inserted into a gap (ie existing was N
, N+3
, we tried N+1
, someone else succeeded N+2
) in which case we retry till we succeed or find 'our' node done by someone else.
It's far more difficult to synchronize deletion; lookup RCU (Read-Copy-Update) for that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.