Right way of synchronizing C and Micropython
Posted: Fri Dec 14, 2018 9:37 pm
Hi,
I'm writing a Micropython module on a multi-threaded platform (ESP32 in this case, but the question is relevant to any other multi-threaded platform).
My module maintains a certain state (a C struct). This state can be changed from *both* Micropython extension functions (written in C), and another thread.
I would like to synchronize changes on my module's state (prevent two threads change the state on the same time). I could use a mutex to protect every Micropython extension.
Instead of doing that, since Micropython is running on a single thread, perhaps I could synchronize with Micropython itself?
I can think of the following options:
- Use `mp_sched_schedule` to schedule any access from another thread. This unfortunately requires me to define extension functions which will only be used by mp_sched_schedule and not the user, since `mp_sched_schedule` is designed to schedule Micropython functions and not C functions .
- Use `MICROPY_BEGIN_ATOMIC_SECTION` (or some other macro/funcion?) on any code that changes my state from another thread. Will that ensure Micropython and my code are synchronized?
- Use a mutex on every Micropython extension
Any suggestions for the right way of doing that?
I'm writing a Micropython module on a multi-threaded platform (ESP32 in this case, but the question is relevant to any other multi-threaded platform).
My module maintains a certain state (a C struct). This state can be changed from *both* Micropython extension functions (written in C), and another thread.
I would like to synchronize changes on my module's state (prevent two threads change the state on the same time). I could use a mutex to protect every Micropython extension.
Instead of doing that, since Micropython is running on a single thread, perhaps I could synchronize with Micropython itself?
I can think of the following options:
- Use `mp_sched_schedule` to schedule any access from another thread. This unfortunately requires me to define extension functions which will only be used by mp_sched_schedule and not the user, since `mp_sched_schedule` is designed to schedule Micropython functions and not C functions .
- Use `MICROPY_BEGIN_ATOMIC_SECTION` (or some other macro/funcion?) on any code that changes my state from another thread. Will that ensure Micropython and my code are synchronized?
- Use a mutex on every Micropython extension
Any suggestions for the right way of doing that?