summaryrefslogtreecommitdiffstatshomepage
path: root/py
diff options
context:
space:
mode:
authorAngus Gratton <angus@redyak.com.au>2024-09-04 17:17:38 +1000
committerDamien George <damien@micropython.org>2024-09-19 13:17:01 +1000
commit52a593cdb14ed732b5580bbed39c0325815adedf (patch)
tree878202bdaacd2ab5cb106a1dda658620a7d6e5bc /py
parent451ba1cf386a2a0874ea20ea593dd6a009ede011 (diff)
downloadmicropython-52a593cdb14ed732b5580bbed39c0325815adedf.tar.gz
micropython-52a593cdb14ed732b5580bbed39c0325815adedf.zip
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>
Diffstat (limited to 'py')
-rw-r--r--py/scheduler.c8
1 files changed, 7 insertions, 1 deletions
diff --git a/py/scheduler.c b/py/scheduler.c
index 3eae8b4fa3..2170b9577e 100644
--- a/py/scheduler.c
+++ b/py/scheduler.c
@@ -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