gpt4 book ai didi

c# - 如何对线程安全队列进行单元测试

转载 作者:太空狗 更新时间:2023-10-30 00:25:36 25 4
gpt4 key购买 nike

我需要一个满足这些要求的简单数据结构:

  • 它应该表现得像一个队列,
  • 所有入队操作都应该是原子的。

我在多线程方面的经验非常有限,但这是我想到的:

public class Tickets
{
private ConcurrentQueue<uint> _tickets;

public Tickets(uint from, uint to)
{
Initialize(from, to);
}

private readonly object _lock = new object();
public void Initialize(uint from, uint to)
{
lock(_lock)
{
_tickets = new ConcurrentQueue<uint>();

for (uint i = from; i <= to; i++)
{
_tickets.Enqueue(i);
}
}
}

public uint Dequeue()
{
uint number;
if (_tickets.TryDequeue(out number))
{
return number;
}

throw new ArgumentException("Ticket queue empty!");
}
}

第一个问题:这段代码可以吗?

第二个问题:我如何对这个类进行单元测试(例如,有两个线程在具有元素(1、2、3、4、5、6)的队列上定期执行出队操作,第一个线程应该只获取奇数和第二个线程只有偶数)?我试过了,但断言没有执行:

[Test]
public void Test()
{
var tickets = new Tickets(1, 4);
var t1 = new Thread(() =>
{
Assert.AreEqual(1, tickets.Dequeue());
Thread.Sleep(100);
Assert.AreEqual(3, tickets.Dequeue());
});


var t2 = new Thread(() =>
{
Assert.AreEqual(2, tickets.Dequeue());
Thread.Sleep(100);
Assert.AreEqual(4, tickets.Dequeue());
});

t1.Start();
t2.Start();
}

最佳答案

我会用国际象棋:http://research.microsoft.com/en-us/projects/chess

CHESS is a tool for finding and reproducing Heisenbugs in concurrent programs. CHESS repeatedly runs a concurrent test ensuring that every run takes a different interleaving. If an interleaving results in an error, CHESS can reproduce the interleaving for improved debugging. CHESS is available for both managed and native programs.

关于c# - 如何对线程安全队列进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16544918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com