我正在尝试编写一个subj队列,但是我遇到了死锁和其他多线程问题。我想使用Interlocked.CompareExchange
来避免使用lock
。但是这段代码没有按预期工作:它只是擦除整个队列。我在这里做错了什么?
public class FixedSizedQueue<T> : IEnumerable<T>
{
readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
public int Limit { get; set; }
public FixedSizedQueue(int limit)
{
Limit = limit;
}
public void Enqueue(T obj)
{
_queue.Enqueue(obj);
if (_queue.Count <= Limit)
return;
int count = _queue.Count;
if (_queue.Count != Interlocked.CompareExchange(ref count, count, _queue.Count))
{
T overflow;
while (_queue.TryDequeue(out overflow))
{
}
}
}
public T[] ToArray()
{
return _queue.ToArray();
}
public IEnumerator<T> GetEnumerator()
{
return _queue.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
也许我只需要另一个只会削减队列的线程......
答案 0 :(得分:1)
Interlocked.CompareExchange
对堆栈变量count
没有意义,因为它是从单线程访问的。我想,你试图在_queue.Count
上使用这个方法,但是由于.Count
是属性而不是简单变量,所以无法编译。所以你需要在你的类中定义计数器。
public class FixedSizedQueue<T> : IEnumerable<T>
{
readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
int CountShadow = 0; // Counter for check constraints.
public int Limit { get; set; }
public FixedSizedQueue(int limit)
{
Limit = limit;
}
public void Enqueue(T obj)
{
/* Update shadow counter first for check constraints. */
int count = CountShadow;
while(true)
{
if(count => Limit) return; // Adding element would violate constraint
int countOld = Interlocked.CompareExchange(ref CountShadow, count, count + 1);
if(countOld == count) break; //Successful update
count = countOld;
}
_queue.Enqueue(obj); // This will update real counter.
}
...
}
此外,您需要为Limit
属性设置自己的setter,这将保持不变CountShadow <= Limit
。或者只是禁止用户在对象构造之后设置该属性。