Skip to content

Fix randomly failing scheduler_tests test

Summary

This closes issue #266 (closed). The root cause is that the original test author was misusing threads and/or synchronization primitives. There is no guarantee that the first main thread runs before the last scheduled task. As such, sometimes, the last task runs and writes "42" into the counter before the BOOST_CHECK_EQUAL(counter, 0) line gets a chance to be evaluated in the main thread.

The fix is to not rely on undefined behavior here and instead do things properly. We just save the counter var to a second atomic and check everything at the end after the two subordinate tasks have all definitely finished running.

Test Plan

  • ninja all check
  • Try and reproduce the issue in #266 (closed) as described. If you can reproduce it against master but not here, then you can be happy this is fixed.

An alternative way to test if you can't reproduce the failure against master is to:

  1. git checkout master
  2. Edit src/test/scheduler_tests.cpp and insert a std::this_thread::sleep_for(std::chrono::milliseconds(21)); right before the line in the schedule_every test that does BOOST_CHECK_EQUAL(counter, 0);. This will reproduce the failure every time.
  3. ninja test_bitcoin && src/test/test_bitcoin -t scheduler_tests
  4. git checkout THIS_MR_BRANCH
  5. Add the sleep call in approximately the same place and do steps (2 & 3) again. You should never get a failure now.

Merge request reports