C# ConcurrentStack实现
我们通过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 = ; public ConcurrentStack(){}
public ConcurrentStack(IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
InitializeFromCollection(collection);
} private void InitializeFromCollection(IEnumerable<T> collection)
{
// We just copy the contents of the collection to our stack.
Node lastNode = null;
foreach (T element in collection)
{
Node newNode = new Node(element);
newNode.m_next = lastNode;
lastNode = newNode;
} m_head = lastNode;
} public void Push(T item)
{
Node newNode = new Node(item);
newNode.m_next = m_head;
if (Interlocked.CompareExchange(ref m_head, newNode, newNode.m_next) == newNode.m_next)
{
return;
}
PushCore(newNode, newNode);
} private void PushCore(Node head, Node tail)
{
SpinWait spin = new SpinWait();
do
{
spin.SpinOnce();
// Reread the head and link our new node.
tail.m_next = m_head;
}
while (Interlocked.CompareExchange(ref m_head, head, tail.m_next) != tail.m_next); } public bool TryPop(out T result)
{
Node head = m_head;
//stack is empty
if (head == null)
{
result = default(T);
return false;
}
if (Interlocked.CompareExchange(ref m_head, head.m_next, head) == head)
{
result = head.m_value;
return true;
}
return TryPopCore(out result);
} private bool TryPopCore(out T result)
{
Node poppedNode; if (TryPopCore(, out poppedNode) == )
{
result = poppedNode.m_value;
return true;
} result = default(T);
return false; }
private int TryPopCore(int count, out Node poppedHead)
{
SpinWait spin = new SpinWait();
Node head;
Node next;
int backoff = ;
Random r = new Random(Environment.TickCount & Int32.MaxValue); // avoid the case where TickCount could return Int32.MinValue
while (true)
{
head = m_head;
// Is the stack empty?
if (head == null)
{
poppedHead = null;
return ;
}
next = head;
int nodesCount = ;
for (; nodesCount < count && next.m_next != null; nodesCount++)
{
next = next.m_next;
} // Try to swap the new head. If we succeed, break out of the loop.
if (Interlocked.CompareExchange(ref m_head, next.m_next, head) == head)
{
poppedHead = head;
return nodesCount;
} // We failed to CAS the new head. Spin briefly and retry.
for (int i = ; i < backoff; i++)
{
spin.SpinOnce();
} backoff = spin.NextSpinWillYield ? r.Next(, BACKOFF_MAX_YIELDS) : backoff * ;
}
}
}
ConcurrentStack<T>里面有一个内部类Node,看到这里我们就知道ConcurrentStack<T>的栈是一开节点Node来做的一个链表,非常好理解。那么线程安全又是怎么做到的了?首先我们来看看Push放法,首先我们需要新实例一个Node,并且新Node的m_next指向现有m_head头节点【newNode.m_next = m_head】,然后在原子比较newNode.m_next 是否是m_head【Interlocked.CompareExchange(ref m_head, newNode, newNode.m_next) == newNode.m_next】,如果是那么把m_head改为newNode ,push操作完成。如果第一个线程newNode.m_next = m_head之后,有新的线程执行了Interlocked.CompareExchange(ref m_head, newNode, newNode.m_next) == newNode.m_next 那么push就需要执行PushCore方法;该方法先自旋一下,然后在Interlocked.CompareExchange(ref m_head, head, tail.m_next) != tail.m_next【这里head和tail是新节点,tail.m_next是指向m_head】,如果当前线程是最新最近的那个 ,那么这个Interlocked.CompareExchange(ref m_head, head, tail.m_next) == tail.m_next就为true,退出循环,否者自旋后再次比较赋值。那么TryPop的实现也是类似的,如果if (Interlocked.CompareExchange(ref m_head, head.m_next, head) == head)成立那么直接返回,否者调用TryPopCore方法。而TryPopCore方法的核心是 if (Interlocked.CompareExchange(ref m_head, next.m_next, head) == head),如果成立则退出,否者自旋,至于自旋的次数来源于for (int i = 0; i < backoff; i++){ spin.SpinOnce(); }。是不是很简单了,但是也很巧妙啊。线程安全依靠SpinWait 的自旋和原子操作Interlocked.CompareExchange来实现的。
C# ConcurrentStack实现的更多相关文章
- .Net中的并行编程-2.ConcurrentStack的实现与分析
在上篇文章<.net中的并行编程-1.基础知识>中列出了在.net进行多核或并行编程中需要的基础知识,今天就来分析在基础知识树中一个比较简单常用的并发数据结构--.net类库中无锁栈的实现 ...
- C#的队列(Queue,ConcurrentQueue)和堆栈(Stack,ConcurrentStack)
一.Queue 表示对象的先进先出(FIFO)集合,非线程安全 常用方法 Dequeue 入队 Enqueue 出队 Contains 队列中是否存在某元素 Clear 清空队列 封装: /// ...
- ConcurrentDictionary,ConcurrentStack,ConcurrentQueue
static void Main(string[] args) { var concurrentDictionary = new ConcurrentDictionary<int, string ...
- .Net多线程编程—并发集合
并发集合 1 为什么使用并发集合? 原因主要有以下几点: System.Collections和System.Collections.Generic名称空间中所提供的经典列表.集合和数组都不是线程安全 ...
- 论C#逼格手册
水文.如何让自己的代码看起来,更有逼格? 要想让自己的代码,看起来更优雅,更有逼格,更高大上,就一定要写出晦涩难懂,而又简洁的代码来. 对于类自身的全局变量,一定要加this,对于基类的,一定要加ba ...
- 写自己的Socket框架(一)
本系列仅介绍可用于生产环境的C#异步Socket框架,如果您在其他地方看到类似的代码,不要惊讶,那可能就是我在参考开源代码时,直接“剽窃”过来的. 1.在脑海里思考一下整个socket的链接的处理流程 ...
- C# - 集合类
C#的集合类命名空间介绍: // 程序集 mscorlib.dll System.dll System.Core.dll // 命名空间 using System.Collections:集合的接口和 ...
- (转)C# 选择正确的集合
原文: http://www.cnblogs.com/luminji/archive/2011/03/24/1993393.html 要选择正确的集合,我们首先要了解一些数据结构的知识.所谓数据结构, ...
- C#并发编程
并发编程,一直是小白变成(●—●)的一个坎.平时也用到过不少并发编程操作,在这里进行一下记录. 多线程并不是唯一 并发:同时做多件事情. 多线程:并发的一种形式,采用多线程来执行程序. 并行处理:把正 ...
随机推荐
- OCM_第七天课程:Section3 —》数据库可用性
注:本文为原著(其内容来自 腾科教育培训课堂).阅读本文注意事项如下: 1:所有文章的转载请标注本文出处. 2:本文非本人不得用于商业用途.违者将承当相应法律责任. 3:该系列文章目录列表: 一:&l ...
- Eclipse通过jdbc连接sqlserver2008数据库的两种方式
数据库登录身份验证方式有两种 其中服务器名称即为安装SQLServer2008的电脑,充当数据库服务器,在笔者这里就是自己的电脑名称. 身份验证方式有两种:windows身份验证和SQLSer ...
- php和NodeJs共存的开发环境
1 折腾 php nodejs 到一起 nodejs当然很火,就像着火了一样,但是必须承认要搭建一个前端的demo开发环境还是PHP靠谱, windows下可以非常的集成套件,比如http://www ...
- 并发之synchronized关键字的应用
并发之synchronized关键字的应用 synchronized关键字理论基础 前两章我们学习了下java内存模型的相关知识, 现在我们来讲讲逢并发必出现的synchronized关键字. 作用 ...
- hdu5358 推公式+在一个区间内的尺取+枚举法
尺取+枚举,推出公式以后就是一个枚举加尺取 但是这题的尺取不是对一个值尺取,而是在一个区间内,所以固定左边界,尺取右边界即可 #include<bits/stdc++.h> #define ...
- canvas简单下雨特效
前面做了两个简单的效果,这次就来个下雨的效果 思路简单的说一下 随机在屏幕中的位置画雨滴,moveTo(x,y) 雨滴的长度就是lineTo(x,y+len) 每次重新绘制页面,就能达到下雨的效果了 ...
- 关于tomcat性能优化
前言 关于 Tomcat 性能调优,一直以来就是运维面试的一个重要话题.今天我们就简单聊聊 Tomcat 如何进行性能优化? 首先声明,我不会去说 Tomcat 是什么,内部结构,原理什么的.我不懂. ...
- 033 关于YARN的HA
一:准备 1.规划 namenode namenode ZKFC ZKFC journalnode journalnode jou ...
- UVa 562 - Dividing coins 均分钱币 【01背包】
题目链接:https://vjudge.net/contest/103424#problem/E 题目大意: 给你一堆硬币,让你分成两堆,分别给A,B两个人,求两人得到的最小差. 解题思路: 求解两人 ...
- 聊聊RPC原理二
之前写了一篇关于RPC的文章,浏览量十分感人:),但是感觉文章写得有些粗,觉得很多细节没有讲出来,这次把里边的细节再次补充和说明. 这次主要说的内容分为: 1. RPC的主要结构图. 2.分析结构图的 ...