嘿,我使用下面的代碼來實現併發堆棧。在下面的代碼中,單獨爲push和pop獲取了鎖,但是這不會使push和pop互相干擾。爲了使棧實現正確,Pop不能與push一起發生,但在push之前或之後(我是否正確?)。但是,如果兩個線程按某種順序調用push和pop,這個程序是否會保持順序?併發堆棧的正確性
public class ConcurrentStackL
{
object _objLock;
internal class Node
{
internal T _item;
internal Node _next;
public Node(T item, Node next) { _item = item; _next = next; }
}
private Node _head = null;
private bool _isEmpty;
public ConcurrentStackL()
{
_head = new Node(default(T), _head);
_objLock = new object();
_isEmpty = true;
}
public void Push(T item)
{
lock (_objLock)
{
_head = new Node(item, _head);
if (!_isEmpty)
_isEmpty = false;
}
}
public T Pop()
{
T item;
lock (_objLock)
{
if (_head._next == null)
throw new IndexOutOfRangeException("Stack is empty");
item = _head._item;
_head = _head._next;
if (_head._next == null)
_isEmpty = true;
}
return item;
}
}
當兩個線程正在運行併發時沒有排序。因此,沒有什麼可以保存的。 – Holger