单元测试基于线程的代码?强制比赛条件 [英] Unit testing thread-based code? Forcing a race condition

查看:42
本文介绍了单元测试基于线程的代码?强制比赛条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用我的应用程序时,我偶然发现某些代码中的竞争条件,该代码使用NSOperationQueue在用户触发的事件之后异步运行任务.我知道如何解决竞争问题,因为这是我不会研究的愚蠢的设计错误,但是我想用一个测试用例来证明该错误(这样它就不会在进一步优化/重构期间再次出现)下线).这让我感到难过.如何测试多线程的东西,特别是在测试的目的是生成竞争条件的情况下?

In using my application, I've stumbled upon a race condition in some code that uses a NSOperationQueue to run tasks asynchronously following user-triggered events. I know how to fix the race condition, since it's a stupid design error that I won't delve into, but I'd like to prove the bug with a test case (so that it doesn't come back during optimizing/refactoring further down the line). This has me stumped. How does one go about testing something that is multi-threaded, especially when the aim of the test is to generate a race condition?

在涉及线程和单元测试时,是否有人链接到我可以参考的参考资料?我对比赛条件生成特别感兴趣.

Does anyone have any links to reference material I can refer to when it comes to dealing with threads and unit testing? I'm particularly interested in race condition generation.

推荐答案

您必须确保导致争用条件的事件序列实际上是在测试过程中出现的.为此,您需要影响测试用例内部的线程交织.

You have to make sure that the sequence of events causing the race condition actually arises during testing. For that, you need to affect the thread interleaving inside the test case.

您可以通过附加的(有条件的)同步或(简单的和不太可靠的)附加计时器来实现.在关键部分中放置一些sleep()调用,以确保它们运行足够长的时间,以使另一个线程进入不良状态.完成工作后,将睡眠调用替换为显式同步(即阻塞一个线程,直到另一个真正确认已到达).

You can achieve that with additional (conditional) synchronization, or, (simpler and less reliable) additional timers. Put some sleep() calls into the critical sections to make sure they run long enough for the other thread to arrive in the undesirable state. When you have that working, replace the sleep calls with explicit synchronization (i.e. block one thread until the other one actually acknowledges to have arrived).

然后以测试用例设置的全局标志为条件.

Then make this all conditional on a global flag that is set by the test case.

这篇关于单元测试基于线程的代码?强制比赛条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆