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
import _thread def thread_entry(arg): print('thread start', arg) for i in range(4): _thread.start_new_thread(thread_entry, (i,))
- 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/)
Code: Select all
git checkout threading cd unix make cd ../tests ./run-tests -d thread
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.