Skip to content

Commit

Permalink
esp32: Sleep one tick in MICROPY_EVENT_POLL_HOOK.
Browse files Browse the repository at this point in the history
If MicroPython threads are enabled, loops waiting for an incoming event
should release the GIL and suspend, allowing other tasks to run while they
wait.

Prior to this commit, the problem can easily be observed by running a
thread that is both busy and regularly releases the GIL (for example a loop
doing something then sleeping a few ms after each iteration).  When the
main task is at the REPL, the thread is significantly stalled.  If the main
task is manually made to release the GIL (for example, by calling
utime.sleep_ms(500)) the other thread can be seen immediately working at
the expected speed again.

Additionally, there are various instances in where blocking functions run
MICROPY_EVENT_POLL_HOOK in a loop while they wait for a certain event/
condition.  For example the uselect methods poll objects to determine
whether data is available, but uses 100% of CPU while it does, constantly
calling MICROPY_EVENT_POLL_HOOK in the process.

The MICROPY_EVENT_POLL_HOOK macro is only ever used in waiting loops, where
(if threads are enabled) it makes sense to yield for a single tick so that
these loops do not consume all CPU cycles but instead other threads may
execute.  (In fact, the thing these loops wait for may even indirectly or
directly depend on another task being able to run.)

This change moves the sleep that was inside the REPL input function to
inside the MICROPY_EVENT_POLL_HOOK macro, where the GIL is already being
released, solving both the blocking REPL issue and the 100% CPU use issue
at the same time.

Signed-off-by: Daniël van de Giessen <daniel@dvdgiessen.nl>
  • Loading branch information
DvdGiessen authored and dpgeorge committed Mar 2, 2022
1 parent 919e586 commit 665f0e2
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 1 deletion.
1 change: 1 addition & 0 deletions ports/esp32/mpconfigport.h
Expand Up @@ -195,6 +195,7 @@ void *esp_native_code_commit(void *, size_t, void *);
mp_handle_pending(true); \
MICROPY_PY_USOCKET_EVENTS_HANDLER \
MP_THREAD_GIL_EXIT(); \
ulTaskNotifyTake(pdFALSE, 1); \
MP_THREAD_GIL_ENTER(); \
} while (0);
#else
Expand Down
1 change: 0 additions & 1 deletion ports/esp32/mphalport.c
Expand Up @@ -98,7 +98,6 @@ int mp_hal_stdin_rx_chr(void) {
return c;
}
MICROPY_EVENT_POLL_HOOK
ulTaskNotifyTake(pdFALSE, 1);
}
}

Expand Down

0 comments on commit 665f0e2

Please sign in to comment.