Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 319
d11wtq Avatar asked Dec 14 '10 03:12

d11wtq


1 Answers

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.

like image 151
Martin v. Löwis Avatar answered Oct 06 '22 05:10

Martin v. Löwis