简体   繁体   中英

Singly-linked list insertion synchronization

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:

  • A thread may only block access to its (immediately) previous node
    (No locking the "whole list")
  • At most O(k) mutexes and condition variables may be used
  • No preemption/interrupts may occur

?

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:

  1. Find insertion point, cur
  2. Create new node (assign prev/next linkage to cur / cur->next )
  3. Atomic op: compare_and_swap(cur->next, new, new->next);
    If fail: if (new->value == next->value) return; // someone beat us to it if (new->value == next->value) return; // someone beat us to it
    Else: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM