Pycom, the people behind the WiPy and LoPy boards, are very generously providing financial support to get multi-threading implemented in MicroPython. This will be a really fantastic feature to have!
Right now this is work in progress. The development is happening on the "threading" branch of the main repository, found here: https://github.com/micropython/micropyt ... /threading . Once it is working smoothly it will be merged into the master branch. [UPDATE: threading branch was merged into master]
The plan is to implement the _thread module, which provides the fundamental functionality for multi-threading: starting new threads and creating mutex objects. For example you will be able to do the following:
Code: Select all
print('thread start', arg)
for i in range(4):
At the time of writing this post the following is implemented:
- a new configuration option: MICROPY_PY_THREAD
- generic _thread module in py/ core (see py/modthread.c, py/mpthread.h)
- a thread safe memory manager and garbage collector (see py/gc.c, especially the GC_ENTER and GC_EXIT macros)
- thread safe NLR handlers (exception handling) for x86 and x86-64
- unix implementation of necessary thread hook functions using pthreads (see unix/mpthreadport.c)
- a test suite (see tests/thread/)
All tests pass on the unix port (x86 and x86-64 CPUs only). You can try them out by doing the following in the root directory of the main repository:
Code: Select all
git checkout threading
./run-tests -d thread
The current implementation does not use a GIL (global interpreter lock). So if you have a 4 core machine then you can have all 4 cores running a Python thread! The threads can even share constant data like ints, floats, tuples and strings. The reason it works without a GIL is because MicroPython does not use reference counting (compared with CPython).
That said, in its current form the unix implementation is not safe to use: there are many operations that you can do that will crash the interpreter. For example, modifying a list that is shared across threads will crash it (they can all read a list without problem). You can protect against such crashes by using a mutex/lock object (which you probably want to do anyway). To see some examples that do work look at the thread tests.
Right now it's not clear whether the VM can remain GIL free. It can in principle, but it will require a lot of work to make everything safe (eg list, dict, set modifications). Certainly though it would be very interesting if MicroPython can have threading without a GIL.
The medium term goal is to apply a simple GIL to make everything safe, and then get threading working on the WiPy. Also pyboard will get threading soon enough. A GIL free VM/runtime may follow in the future. Note that having a GIL on bare-metal ports like WiPy and pyboard doesn't really make a difference (compared with no GIL) because there is only 1 CPU core to make use of.