zoukankan      html  css  js  c++  java
  • 轻量级 Lock Free 线程安全的 Queue<T> 的C#2.0实现

    最近在维护一些C# 2.0的代码....发现各种线程不安全的实现

    2.0里面又没有ConcurrentCollection的相关类

    不得已,自己写了一个,

    本来想用传统的lock实现的, 不过考虑到其中的操作非常轻量级...最终还是用了Lock Free

    使用原子操作 InterLocked 替换掉常用的lock关键字

        public sealed class SafedQueue<T>
    {
    #region private Fields
    private int isTaked = 0;
    private Queue<T> queue = new Queue<T>();
    private int MaxCount = 1000 * 1000;
    #endregion

    public void Enqueue(T t)
    {
    try
    {
    while (Interlocked.Exchange(ref isTaked, 1) != 0)
    {
    }
    this.queue.Enqueue(t);
    }
    finally
    {
    Thread.VolatileWrite(ref isTaked, 0);
    }
    }

    public T Dequeue()
    {
    try
    {
    while (Interlocked.Exchange(ref isTaked, 1) != 0)
    {
    }
    T t = this.queue.Dequeue();
    return t;
    }
    finally
    {
    Thread.VolatileWrite(ref isTaked, 0);
    }
    }

    public bool TryEnqueue(T t)
    {
    try
    {
    for (int i = 0; i < MaxCount; i++)
    {
    if (Interlocked.Exchange(ref isTaked, 1) == 0)
    {
    this.queue.Enqueue(t);
    return true;
    }
    }
    return false;
    }
    finally
    {
    Thread.VolatileWrite(ref isTaked, 0);
    }
    }

    public bool TryDequeue(out T t)
    {
    try
    {
    for (int i = 0; i < MaxCount; i++)
    {
    if (Interlocked.Exchange(ref isTaked, 1) == 0)
    {
    t = this.queue.Dequeue();
    return true;
    }
    }
    t = default(T);
    return false;
    }
    finally
    {
    Thread.VolatileWrite(ref isTaked, 0);
    }
    }
    }

    Try起头的方法都有尝试次数限制,超过限制以后就退出并返回false

  • 相关阅读:
    文件的上传
    自定义EL表达式的函数
    JSTL 自定义标签
    Java c3p0连接池之二
    Java c3p0连接池
    JSP 登录与注册的小案例
    Java jdbc 连接oracle之三(封装工具类)
    Java jdbc 连接oracle之二(使用properties文件)
    Swift中Notification.Name自定义枚举
    swift UITableViewCell 策划删除,iOS11之后 设置侧滑不到最左边
  • 原文地址:https://www.cnblogs.com/PurpleTide/p/2404608.html
Copyright © 2011-2022 走看看