FIFO信号量测试
我已经实现了 FIFO 信号量,但现在我需要一种方法来测试/证明它们正常工作。一个简单的测试是创建一些线程,尝试等待信号量,然后打印带有数字的消息,如果数字按顺序排列,则应该是 FIFO,但这不足以证明这一点,因为该顺序可能有偶然发生的。因此,我需要一种更好的方法来测试它。
如果需要,也可以使用锁或条件变量。
谢谢
I have implemented FIFO semaphores but now I need a way to test/prove that they are working properly. A simple test would be to create some threads that try to wait on a semaphore and then print a message with a number and if the numbers are in order it should be FIFO, but this is not good enough to prove it because that order could have occurred by chance. Thus, I need a better way of testing it.
If necessary locks or condition variables can be used too.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您用句子“但这还不足以证明这一点,因为该顺序可能是偶然发生的”所描述的在某种程度上是一个已知的困境。
1) 即使您有规范,您也不能确保该规范符合您的意图。为了说明这一点,我将举一个“正确性的限制”中的例子。让我们考虑一下因式分解函数的规范:
但这还不够,因为您可以有一个返回
A=1
和B=C
的实现。添加A,B != 1
仍然会导致A=-1
和B=-C
,因此唯一正确的规范必须声明 <代码>A,B>1。这只是为了说明编写符合真实意图的规范是多么复杂。2) 即使证明算法,仍然不意味着实现在实践中是正确的。 Donald Knuth 的这句话最好地说明了这一点:
3) 测试只能揭示错误的存在,而不能揭示错误的不存在。这句话可以追溯到 Dijkstra:
结论:你注定要失败,你永远无法 100% 确定你的代码按照其意图是正确的!但事情并没有那么糟糕。对代码有很高的信心通常就足够了。例如,如果使用多个线程对您来说仍然不够,您可以决定也使用模糊测试,以便更加随机地执行测试。如果您的测试总是通过,那么您可以非常确信您的代码是好的。
What you describe with your sentence "but this is not good enough to prove it because that order could have occurred by chance" is somehow a known dilema.
1) Even if you have a specification, you can not ensure that the specification match your intention. To illustrate this I will take an example from "the limit of correctness". Let's consider a specification for a factorization function that is:
But it's not enough as you could have an implementation that returns
A=1
andB=C
. AddingA,B != 1
can still lead toA=-1
andB=-C
, so the only correct specification must stateA,B>1
. That's just to illustrate how complicated it can be to write a specification that match the real intention.2) Even having proved an algorithm, still doesn't mean the implementation is correct in practice. This is best illustrated with this quote from Donald Knuth:
3) Testing can only reveal the presence of bug, not their absence. This quote goes back to Dijkstra:
Conclusion: you are doomed and you will never be 100% sure that your code is correct according to its intent! But stuff aren't that bad. Having a high confidence about the code is usually enough. For instance, if using multiple threads is still not enough for you, you can decide to use fuzzing as well so as to randomize the test execution even more. If your tests always pass, well, you can be pretty confident that your code is good.
您可以运行测试几次,例如 10 次,并测试每次顺序是否正确。这将确保它的发生不是偶然的。
PS 通常避免单元测试中的多线程
You can run the test a few times, e.g. 10, and test that each time the order was correct. This will ensure that it happened not by chance.
P.S. Multiple threads in a unit test is usually avoided