C# ConcurrentStack实现

本文探讨了C#中ConcurrentStack的数据结构和线程安全机制。通过内部类Node实现的链表结构保证了基础操作,利用Interlocked.CompareExchange方法和SpinWait自旋确保线程安全。Push和TryPop操作通过原子比较和自旋等待来完成并发环境下的栈操作。
摘要由CSDN通过智能技术生成

我们通过C# Queue 和Stack的实现知道Stack是依靠数组实现的,那么ConcurrentStack的栈又是如何实现的了,然后它的线程安全又是怎么做到的了? 来看看其code吧

 public class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
    {
        private class Node
        {
            internal readonly T m_value; // Value of the node.
            internal Node m_next; // Next pointer.
            internal Node(T value)
            {
                m_value = value;
                m_next = null;
            }
        }
        private volatile Node m_head; 
        private const int BACKOFF_MAX_YIELDS = 8;
        
        public ConcurrentStack(){}
        public ConcurrentStack(IEnumerable<T> collection)
        {
            if (collection == null)
            {
                throw 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值