[英]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. 假设我有一个排序的,单链接的N个整数列表,其中没有重复项,并且k个线程(其中k << N ),每个都尝试将一些整数(大于头节点)插入到列表中。
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. 首先,如果插入集合只是一个非常罕见的任务,那么链表不是一个很好的解决方案 - 因为找到插入点是O(N)
操作,即使对于排序列表,因此最终缩放严重。
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
/ cur->next
) 创建新节点(指定上一个/下一个链接到cur
/ cur->next
) compare_and_swap(cur->next, new, new->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
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) 否则: cur = cur->next
并重复跳舞(列表已排序,有人插在我们面前) 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. 即尝试链接新节点的结果是要么我们成功,要么有人打败我们插入相同的节点(在这种情况下我们没有 - 它已经存在),或有人插入间隙(即现有的是N
, N+3
,我们尝试了N+1
,其他人成功了N+2
)在这种情况下我们重试直到我们成功或者找到其他人完成的“我们的”节点。
It's far more difficult to synchronize deletion; 同步删除要困难得多; lookup RCU (Read-Copy-Update) for that. 查找RCU(读取 - 复制 - 更新)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.