【发布时间】:2011-05-06 21:03:03
【问题描述】:
我知道链表不是线程安全的,在工作中我被要求编写一个简单的线程安全链表。
由于我不会经历各种复杂情况,我不能简单地包装一个 LinkedList,而是需要编写一个 LinkedList 的实现
我猜我需要这个,但我如何才能以线程安全的方式实际实现一个枚举器(用于 linedlist)?
public class LinkedlistNode
{
private LinkedlistNode next;
private T item;
/// <summary>
/// Constructor for a new LinklistNode
/// </summary>
/// <param name="node">The node item to create</param>
public LinkedlistNode(T node)
{
next = null;
item = node;
}
/// <summary>
/// Shows the next item in the collection (or shows null for the the last item)
/// </summary>
public LinkedlistNode Next
{
get { return next; }
set { next = value; }
}
/// <summary>
/// The contents of the list
/// </summary>
public T Item
{
get { return item; }
set { item = value; }
}
}
【问题讨论】:
-
看起来你有一个单链表。如果您通过取出属性上的设置器使其不可变,那么您的链接列表将本质上是线程安全的。您可以在FSharp.Core.dll 中找到已经为您实现的一个。
-
我需要能够添加和删除项目 :)
-
如果另一个线程试图从列表中添加或删除一个项目,而一个线程正在枚举它,会发生什么?
-
为了有效地删除项目,您需要一个双向链表。否则,您必须通过从头开始并遍历直到找到其下一项为当前节点的节点来获取要删除的节点的所有者。 Previous 属性采用该线性运算并使其保持不变。
-
使用单链接不可变列表很容易将项目添加到前面 - 只需创建一个节点,其中
next指向现有列表的第一个节点。删除一个节点(或在中间添加)需要重新生成该节点之前的所有节点,这是真的。
标签: c# multithreading