1 public class DoubleCacheQueue
2 {
3
4 public DoubleCacheQueue()
5 { }
6 public T Dequeue()
7 {
8 T t = default(T);
9
10 if (readQueue.Count > 0)
11 t= readQueue.Dequeue();
12 else
13 {
14 writeQueue = Interlocked.Exchange(ref readQueue, writeQueue);
15 }
16 return t;
17 }
18 public void Enqueue(T item)
19 {
20 writeQueue.Enqueue(item);
21 }
22
23 public int Count
24 {
25 get { return readQueue.Count; }
26 }
27 //讀緩沖
28 private Queue readQueue = new Queue();
29 //寫緩沖
30 private Queue writeQueue = new Queue();
31
32 }
?
補充下: 我應用的場景就是只有2個線程,我想實現一個lock free的隊列 一個讀線程不停的Dequeue 一個寫線程不停的Enqueue 在只有2個線程一個單線程讀和一個單線程寫的情況下,能不能雙線程安全?
5 回答

慕姐8265434
TA貢獻1813條經驗 獲得超2個贊
MSDN說的很清楚了,Queue的Item如果是公共靜態的就是線程安全的。否則自己保證。
Queue本身不保證枚舉的線程安全。so 你這么做不是線程安全的。
可以考慮用ConcurrentQueue?類或者使用synchronized方法。

有只小跳蛙
TA貢獻1824條經驗 獲得超8個贊
@garry:?
public virtual object Dequeue()
{
if (this.Count == 0)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyQueue"));
}
object obj2 = this._array[this._head];
this._array[this._head] = null;
this._head = (this._head + 1) % this._array.Length;
this._size--;
this._version++;
return obj2;
}
public virtual void Enqueue(object obj)
{
if (this._size == this._array.Length)
{
int capacity = (int) ((this._array.Length * this._growFactor) / 100L);
if (capacity < (this._array.Length + 4))
{
capacity = this._array.Length + 4;
}
this.SetCapacity(capacity);
}
this._array[this._tail] = obj;
this._tail = (this._tail + 1) % this._array.Length;
this._size++;
this._version++;
}
幫你看了下內部代碼,
1、他們使用了公用資源?this._head和this._tail 。
2、這兩個方法沒有臨界區
3、這兩個變量的計算沒有使用原子操作
?
所以,多線程使用這兩個方法會出現并發問題。
- 5 回答
- 0 關注
- 547 瀏覽
添加回答
舉報
0/150
提交
取消