Skip to content

unix/mphal: Prevent REPL from blocking - #4953

Closed
amirgon wants to merge 8 commits into
micropython:masterfrom
amirgon:unix_repl_fix
Closed

amirgon wants to merge 8 commits into
micropython:masterfrom
amirgon:unix_repl_fix

Conversation

@amirgon

@amirgon amirgon commented Jul 27, 2019

Copy link
Copy Markdown
Contributor

When the REPL is waiting for user input, it is blocking-read from stdin. Micropython event on the same thread would have to wait for the user to interact

This change prevents read from blocking by first making sure there is something to read, otherwise it polls and handles Micropython pending events (mp_handle_pending)

This is in line with other port's REPLs such as ESP32, which do not block

When the REPL is waiting for user input, it is blocking-read from stdin. Micropython event on the same thread would have to wait for the user to interact

This change prevents read from blocking by first making sure there is something to read, otherwise it polls and handles Micropython pending events (mp_handle_pending)

This is in line with other port\'s REPLs such as ESP32, which do not block
Comment thread ports/unix/unix_mphal.c Outdated
}
#endif

static bool inputAvailable()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this should be inputAvailable(void) to be consistent with other functions?

@stinos stinos Jul 28, 2019 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, and also input_available(void), please check the code style from the surrounding functions. Also for the rest: opening brace on same line, spaces around +

Comment thread ports/unix/unix_mphal.c Outdated
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
return (FD_ISSET(0, &fds));

@stinos stinos Jul 28, 2019 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure the the extra brackets are needed?

@amirgon

amirgon commented Jul 28, 2019

Copy link
Copy Markdown
Contributor Author

@embeddedt @stinos Fixed according to your comments.

@embeddedt

Copy link
Copy Markdown

@amirgon I think @stinos would like the function to be named input_available rather than inputAvailable. It doesn't appear that camel case is used in MicroPython.

@amirgon

amirgon commented Jul 28, 2019

Copy link
Copy Markdown
Contributor Author

@amirgon I think @stinos would like the function to be named input_available rather than inputAvailable. It doesn't appear that camel case is used in MicroPython.

@embeddedt Just missed that. Fixed now.

@stinos

stinos commented Jul 29, 2019

Copy link
Copy Markdown
Contributor

You still missed the opening brace for the while loop :)

@dpgeorge

Copy link
Copy Markdown
Member

When the REPL is waiting for user input, it is blocking-read from stdin. Micropython event on the same thread would have to wait for the user to interact

Are you able to provide an example of such an event? An event like a timer expiry would trigger an asynchronous signal which can execute even during the blocking read. And such a signal should also make the read call terminate with EINTR. So it'd be good to see an example where the blocking read actual blocks the events.

@amirgon

amirgon commented Jul 29, 2019

Copy link
Copy Markdown
Contributor Author

Are you able to provide an example of such an event?

@dpgeorge - Any event that schedules uPy, by calling mp_sched_schedule.
This is needed when we want to keep the application single threaded, but still want to handle events asynchronously.

Specifically, I'm working on LittlevGL Micropython Bindings. It's designed to be single threaded, but lvgl requires periodic calls to lv_task_handler, which in turn may execute uPy code.

On embedded architectures a timer interrupt schedules lv_task_handler, and we would like the unix port to behave similarly.
On the unix port we schedule it from a different thread every 1 millisecond.

Without this fix, the GUI would "freeze" during blocking read from stdin.

@dpgeorge

Copy link
Copy Markdown
Member

On embedded architectures a timer interrupt schedules lv_task_handler, and we would like the unix port to behave similarly.
On the unix port we schedule it from a different thread every 1 millisecond.

You can use unix signals to execute a callback asynchronously. See micropython-lib/machine/machine/timer.py for code that does that (in Python). Even at the blocking REPL it will still execute a signal callback.

The deeper issue here is power consumption and the ability to idle when there is nothing going on. If MicroPython is responsible for running an event loop on idle then there's not much of a chance to sleep. Eg in an embedded system it should be possible to sleep the MCU until an event (IRQ) arrives, at which point it can be processed, then go back to sleep. For things that require continual work (like a graphics system) there can be a timer that fires an event at regular intervals, but at least it's still event based, not polling based.

You can see the above problem with the PR here: when the unix executable is running at an idle prompt it now has about 10-15% CPU load, compared to 0% before this PR.

Comment thread ports/unix/unix_mphal.c Outdated
#endif
while (!input_available()) {
mp_handle_pending();
usleep(1);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problems @dpgeorge has mentioned would effectively disappear if we slept for 1 or 10 milliseconds instead of 1 microsecond.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@embeddedt I would first like to try his suggestion executing uPy asynchronously without calling mp_sched_schedule.

@amirgon

amirgon commented Jul 30, 2019

Copy link
Copy Markdown
Contributor Author

You can use unix signals to execute a callback asynchronously. See micropython-lib/machine/machine/timer.py for code that does that (in Python). Even at the blocking REPL it will still execute a signal callback.

@dpgeorge The problem is that there is no uPy thread context when I call the asynchronous function.
I cannot use mp_thread_create since SDL functions can only be called within SDL threads, so I need to start a thread by SDL_CreateThread instead, and call uPy from there.

So I copied some code from thread_entry (in py/modthread.c) and ended up with something like this:

typedef struct _thread_data_t
{
    size_t stack_size;
    mp_obj_dict_t *locals;
    mp_obj_dict_t *globals;
} thread_data_t;
 
STATIC int thread_entry(void *_data) {
    thread_data_t *data = _data;

    // Execution begins here for a new thread.  We do not have the GIL.

    mp_state_thread_t ts;
    mp_thread_set_state(&ts);

    mp_stack_set_top(&ts + 1); // need to include ts in root-pointer scan
    mp_stack_set_limit(data->stack_size);

    // set locals and globals from the calling context
    mp_locals_set(data->locals);
    mp_globals_set(data->globals);

    MP_THREAD_GIL_ENTER();

    nlr_buf_t nlr;
    if (nlr_push(&nlr) == 0) {
        tick_thread(NULL);
        nlr_pop();
    } else {
        // uncaught exception
        // check for SystemExit
        mp_obj_base_t *exc = (mp_obj_base_t*)nlr.ret_val;
        if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(exc->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
            // swallow exception silently
        } else {
            // print exception out
            mp_printf(MICROPY_ERROR_PRINTER, "Unhandled exception in SDL thread!\n");
            mp_obj_print_exception(MICROPY_ERROR_PRINTER, MP_OBJ_FROM_PTR(exc));
        }
    }

    MP_THREAD_GIL_EXIT();

    return 0;
}
...
...
{
    static thread_data_t thread_data;
    thread_data = (thread_data_t){SDL_THREAD_STACK_SIZE, mp_state_ctx.thread.dict_locals, mp_state_ctx.thread.dict_globals};
    SDL_CreateThread(thread_entry, "tick", &thread_data);

}

Very verbose and far from the one-liner I had before, when using mp_sched_schedule.
But it works, with some quirks.

For the record, I still think it's worth allowing polling, even optionally, to make things simpler.

Closing.

@amirgon amirgon closed this Jul 30, 2019
@embeddedt

Copy link
Copy Markdown

For the record, I still think it's worth allowing polling, even optionally, to make things simpler.

I agree. On a modern processor, the load of waking up every 10ms should not be of concern, in my opinion.

@dpgeorge

Copy link
Copy Markdown
Member

For the record, I still think it's worth allowing polling, even optionally, to make things simpler.

I think the way to do it efficiently would be to poll on stdin with no timeout (ie forever) in a loop until data is ready, and in that loop call mp_handle_pending(). Any signals will interrupt the poll and allow mp_handle_pending() to run.

@amirgon

amirgon commented Jul 31, 2019

Copy link
Copy Markdown
Contributor Author

Any signals will interrupt the poll and allow mp_handle_pending() to run.

@dpgeorge The GUI needs to update every few milliseconds. Do you suggest we raise a signal every few milliseconds, to interrupt the poll? Isn't that intrusive?
Because in the general case, we don't know what the user code is running on the main thread.

Suppose the user code is waiting for some signal he is generating. He doesn't expect a signal to come from someplace else (unless this is "SIGTERM" or something that can be expected from the OS).
Moreover, if the signal is handled on user code, it might never reach our polling loop at all.

@embeddedt

Copy link
Copy Markdown

Plus, IMO, raising a signal every 10ms and sleeping for 10ms take up roughly the same CPU time.

@jimmo

jimmo commented Jul 31, 2019

Copy link
Copy Markdown
Member

@dpgeorge The GUI needs to update every few milliseconds. Do you suggest we raise a signal every few milliseconds, to interrupt the poll? Isn't that intrusive?

That does sound like what he's suggesting. And at some level, that's pretty much how sleep works anyway.

I think the main point is that the signal and the interval becomes completely up to your program or use case. It doesn't matter which signal you use, and you don't even have to handle it anywhere, as long as it results in read() returning EINTR.

You could use timer_create() to make a periodic timer with a signal number and interval of your choice, and only when littlevgl is running -- but importantly this means that the behaviour is unchanged for everyone else. (And timer_create() is exactly what machine/machine/timer.py uses, so you can do all this from Python if you choose).

Plus, IMO, raising a signal every 10ms and sleeping for 10ms take up roughly the same CPU time.

Maybe, but they're vastly different in terms of program behaviour. Sleeping for 10ms means you now have a per-byte latency of up to 10ms. Probably not a big deal for the repl, but the point above is that the sleep implementation would mean that all users of the unix port now get this, whereas the signal is only raised if you choose to (i.e. because your program needs it). And remember the unix port can be used on quite a wide range of devices, not just modern PC CPUs.

Just throwing it out there though, a third alternative: I notice that the way input_available() in this PR works is to do a non-blocking select() on the stdin FD, then sleep if nothing is available. However, you could set a timeout on select() instead, avoiding the need for the sleep. (But I think the signal approach is a better idea, because it gives control of the interval to whatever code needs it).

@dpgeorge

Copy link
Copy Markdown
Member

I agree with @jimmo 's comments above.

The way to do it efficiently is to only raise a signal (and hence EINTR the select/poll/read) when needed. Eg if mp_sched_schedule() is called then also raise a signal so that main thread can be interrupted from its sleep if needed (and this will still work even if the main thread is executing code in the VM, for example).

@amirgon

amirgon commented Jul 31, 2019

Copy link
Copy Markdown
Contributor Author

and only when littlevgl is running -- but importantly this means that the behaviour is unchanged for everyone else.

@jimmo littlevgl is a library, not the application itself.
Above it, there's some arbitrary user application (possibly started from the REPL).
You say: "importantly this means that the behaviour is unchanged for everyone else", but I think that this should include that arbitrary user application which uses littlevgl.

My point is that raising a signal might be intrusive towards a user application. That user application might not expect us to send this signal, and it would affect its flow.

What you suggest would require any application that uses littlevgl to be aware that signals are raised. For example, if someone calls "read" in his application, he would need to take into account a possible EINTR result.

(btw, using a separate thread for the GUI event loop can prevent this, but introduces thread safety issues)

@dpgeorge

Copy link
Copy Markdown
Member

For EINTR see related PEP 475 https://www.python.org/dev/peps/pep-0475/ and #3268

@amirgon

amirgon commented Jul 31, 2019

Copy link
Copy Markdown
Contributor Author

It doesn't matter which signal you use, and you don't even have to handle it anywhere

Ok. I tried your suggestion to raise a signal. It didn't go so smooth.
Apparently - it does matter which signal I choose:

  • First attempt: SIGALRM: Program terminated with signal SIGALRM, Alarm clock.
  • Next attemp: SIGUSR1: micropython: ../../py/gc.c:588: gc_free: Assertion ATB_GET_KIND(block) == AT_HEAD' failed.
    This is probably related to dbd54e0, but I didn't debug it further.
  • Next attempt: SIGUSR2 : Terminates with "User defined signal 2". I had to add sigaction(SIGUSR2, &sa, NULL); on mp_thread_init to make this work.

So it works now with SIGUSR2.
But one day, someone decides to use SIGUSR2 in Micropython for some other purpose (the same way SIGUSR1 is used today for gc), and then SIGUSR2 might stop working too.

Another annoyance: When running with gdb, it stops by default on SIGUSR2, so whoever uses gdb would have to run handle SIGUSR2 noprint nostop

@dpgeorge, @jimmo - Are you still convinced that using signal is the right way to do this?

@embeddedt

Copy link
Copy Markdown

@amirgon Yes, it does matter which signal you choose; some of them just terminate the process (ab)normally.

https://pubs.opengroup.org/onlinepubs/009695399/basedefs/signal.h.html

@amirgon

amirgon commented Jul 31, 2019

Copy link
Copy Markdown
Contributor Author

@amirgon Yes, it does matter which signal you choose; some of them just terminate the process (ab)normally.

https://pubs.opengroup.org/onlinepubs/009695399/basedefs/signal.h.html

Yes I was referring to @jimmo's claim that "it doesn't matter which signal you use", but I think both him and me took for granted that we shouldn't use a signal that terminates the process...

My point is that even other "innocent" signals create some problems.

@embeddedt

Copy link
Copy Markdown

If it can be documented that certain signals are reserved for MicroPython/lv_micropython (i.e. SIGUSR1 because it triggers GC), then I don't see an issue with using SIGUSR2.

amirgon added 2 commits August 3, 2019 00:04
Added SIGUSR2 and SIGALRM sigaction, to prevent them from killing the application which is the default behavior
@amirgon amirgon reopened this Aug 2, 2019
@amirgon

amirgon commented Aug 2, 2019

Copy link
Copy Markdown
Contributor Author

Reopned.

Changed implementation to signal, as @dpgeorge and @jimmo suggested.
This required adding signals to sigaction otherwise signals terminate the application.
Currently I've added SIGUSR2 and SIGALRM.

Comment thread ports/unix/mpthreadport.c Resolved
The user would need to call sigaction in user code.  
Calling sigaction is required, to prevent signals default behavior of terminating the application.  
sigaction can be called from either C or Python code with ffi. See https://github.com/micropython/micropython-lib/tree/master/signal
@amirgon

amirgon commented Sep 10, 2019

Copy link
Copy Markdown
Contributor Author

@dpgeorge Is anything still wrong or missing?

After my last commit, a month ago, the change is very small and straightforward:

        int ret;
        do {
            mp_handle_pending();
            ret = read(0, &c, 1);
        } while (ret == -1 && errno == EINTR);

(I removed the calls to sigaction)

@dlech

dlech commented Mar 5, 2020

Copy link
Copy Markdown
Contributor

Alternate implementation in #5723

@amirgon

amirgon commented Jul 4, 2020

Copy link
Copy Markdown
Contributor Author

#5723 is a good solution for this problem.

Special considerations when using this:

  • Need to select a user defined signal such as SIGUSR1
  • Need to register a signal handler with sigaction (even with an empty handler), to prevent application from exiting and generate EINTR on blocking function calls when signal is received.
  • On multithreaded applications, need to send the signal to the micropython thread. (pthread_kill instead of raise)

@amirgon amirgon closed this Jul 4, 2020
amirgon added a commit to amirgon/lv_bindings that referenced this pull request Jul 4, 2020
Remove mp_instance_cast_to_native_base and MP_ERROR_TEXT defines from lv_conf.h

small fixes in gen_mpy.py

SDL: use signals instead of polling when waiting to user input, see micropython/micropython#4953 (comment)

Advanced demo: improve gradient to work better with ili9341
amirgon added a commit to amirgon/lv_bindings that referenced this pull request Jul 4, 2020
Remove mp_instance_cast_to_native_base and MP_ERROR_TEXT defines from lv_conf.h

small fixes in gen_mpy.py

SDL: use signals instead of polling when waiting to user input, see micropython/micropython#4953 (comment)

Advanced demo: improve gradient to work better with ili9341
tannewt pushed a commit to tannewt/circuitpython that referenced this pull request Jul 9, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants