0

I'm writing unit tests for a Python multithreaded program. Unit testing multithreaded programs is always difficult, but I have it working pretty well. One issue I have is that since the Python threads take turns, instead of running in parellel or time sliced, I often find myself writing tests like:

# Act
object_being_tested.do_function_that_triggers_other_thread_to_run()
time.sleep(0.1)  # Let the worker thread run

# Verify    
self.assertEqual(value_that_worker_thread_should_have_set, object_being_tested.get_value())

# Cleanup
object_being_tested.worker_thread.join()

This works pretty well but the 'time.sleep(0.1)' seems awkward to me. Is there a clean way in python to indicate that I don't want to sleep, I just want to switch away from the current thread and let the other thread run? Or is a short sleep the best way?

Bill Shubert
  • 496
  • 3
  • 12
  • "Unit testing multithreaded programs is always difficult" yup. to me your options are: 1. set a flag variable that the computation is done and poll until that variable is changed before calling `get_value` 2. actually just `join` the thread. 3. create a separate mutex (similar to 1) that you can `acquire`. 4. Keep what you've got if it works... – Aaron Jun 10 '23 at 22:14
  • 1
    Does this answer the question? https://stackoverflow.com/questions/1908206/in-there-something-similar-to-javas-thread-yield-in-python-does-that-even-ma – Jeremy Friesner Jun 10 '23 at 23:37

0 Answers0