py/scheduler: Only run callbacks on the main thread if GIL is disabled.

Otherwise it's very difficult to reason about thread safety in a
scheduler callback, as it can run at any time on any thread - including
racing against any bytecode operation on any thread.

This work was funded through GitHub Sponsors.

Signed-off-by: Angus Gratton <angus@redyak.com.au>
This commit is contained in:
Angus Gratton
2024-09-04 17:17:38 +10:00
committed by Damien George
parent 451ba1cf38
commit 52a593cdb1
2 changed files with 15 additions and 1 deletions

View File

@@ -236,7 +236,13 @@ void mp_handle_pending(bool raise_exc) {
// Handle any pending callbacks.
#if MICROPY_ENABLE_SCHEDULER
if (MP_STATE_VM(sched_state) == MP_SCHED_PENDING) {
bool run_scheduler = (MP_STATE_VM(sched_state) == MP_SCHED_PENDING);
#if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL
// Avoid races by running the scheduler on the main thread, only.
// (Not needed if GIL enabled, as GIL ensures thread safety here.)
run_scheduler = run_scheduler && mp_thread_is_main_thread();
#endif
if (run_scheduler) {
mp_sched_run_pending();
}
#endif