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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With