Executing MicroPython program in non-blocking fashion

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
mvladic
Posts: 3
Joined: Sun Jan 30, 2022 1:22 pm

Executing MicroPython program in non-blocking fashion

Post by mvladic » Sun Jan 30, 2022 2:43 pm

If I call "mp_call_function_0(...)" my program is blocked until that function returns (i.e. when MP program finishes). Is it possible to execute MP program in non-blocking fashion? Something like "mp_call_function_0_start(...)" and it returns immediately and later I call "mp_call_function_0_continue(...)" multiple times until it says that MP code execution is done.

KJM
Posts: 158
Joined: Sun Nov 18, 2018 10:53 pm
Location: Sydney AU

Re: Executing MicroPython program in non-blocking fashion

Post by KJM » Sun Jan 30, 2022 11:10 pm

Not sure if this is what you're after

Code: Select all

import time, _thread

def some_fn(caller, delay):
    print('some_fn called by', caller)
    time.sleep(delay)
    print('some_fn is finished')
    
_thread.start_new_thread(some_fn, ('main program', 2))
print('main program called some_fn & continues')
time.sleep(3)
print('main program still running')
still new to this myself

Code: Select all

>>> %Run -c $EDITOR_CONTENT
main program called some_fn & continues
some_fn called by main program
some_fn is finished
main program still running
>>> 

bulletmark
Posts: 59
Joined: Mon Mar 29, 2021 1:36 am
Location: Brisbane Australia

Re: Executing MicroPython program in non-blocking fashion

Post by bulletmark » Mon Jan 31, 2022 4:01 am

It is better to use asyncio, particularly on MicroPython. Here is the same code posted by KJM using asyncio instead:

Code: Select all

import uasyncio as asyncio

async def some_fn(caller, delay):
    print('some_fn called by', caller)
    await asyncio.sleep(delay)
    print('some_fn is finished')

async def main():
    asyncio.create_task(some_fn('main program', 2))
    print('main program called some_fn & continues')
    await asyncio.sleep(3)
    print('main program still running')

asyncio.run(main())

mvladic
Posts: 3
Joined: Sun Jan 30, 2022 1:22 pm

Re: Executing MicroPython program in non-blocking fashion

Post by mvladic » Mon Jan 31, 2022 8:13 am

This is more of a question how to run embedded MicroPython interpreter inside some firmware and not how to write MicroPython code. I don't want my firmware to be blocked while python interpreter is running. I could use for example FreeRTOS and run MP interpreter in another thread, but if I have single threaded firmware I'm wondering is it possible at the same time to run both MicroPython interpreter and some other firmware code independent from MicroPython interpreter.

Post Reply