开发者

Unit testing thread-based code? Forcing a race condition

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 bu开发者_JS百科g 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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜