輕量級 Lock Free 線程安全的 Queue 的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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM