State of application thread support?



I’m looking into using application threads on an electron (v0.7.0-rc.7).

I found various posts regarding application threads:

I found posts regarding the ‘spark_wiring_thread.h’ which provides an undocumented implementation for creating Threads. The code is there for quite a while, but it looks like still not officially documented/supported. Is this the way to create application threads?

I also found a post that mentions making C++11 std::thread available to the application as they are already used and mapped to the HAL for the system firmware. Is there an update on this?

What is the way to use application threads?
I appreciate any hints and insides.

Thanks and regards


Application threads work, and have since around 0.4.8, on the Photon and Electron. They’re based on FreeRTOS currently. The API in spark_wiring_thread.h is more or less implementation neutral and uses the Particle HAL.

The two biggest caveats are:

  • You can’t stop a thread
  • Most APIs are not thread safe

There’s also a fundamental limitation of threads on a micro controller. Each thread needs to have its own stack. If you want a stack as large as the main loop thread (6144 bytes), you’ll use the 60K of available RAM in no time. It’s not like Windows/Linux/Mac where you can allocate a 1 MB stack for a thread and let the virtual memory manager deal with it. There is no virtual memory on the Photon/Electron.

I prefer to use state machines over threads for these reasons, but threads do work and in certain situations they might make sense.


@rickkas7 thanks for your feedback. It triggers some more questions:

So for a particle application you suggest to use a state machines and event based programming approach rather than the threading approach?
How do you suggest to work around some of the synchronous firmware calls of particle like a Particle.publish() or TCPClient.connect()?
Are there async counterparts for these synchronous calls so that a state/event based non blocking programming is possible?
Are there plans to add a supporting infrastructure for event based programming, something like the mbed-events library?



Yes, with only a few exceptions I think a finite state machine or chained callbacks is the way to go.

If you pre-flight Particle.publish with a test for Particle.connected(), use SYSTEM_THREAD(ENABLED) and do not use WITH_ACK, Particle.publish won’t block.

TCPClient.connect is one that’s really hard to work around, and is annoying. It’s actually one place where I think a thread is necessary, and I have an asynchronous implementation of TCPClient connect that does that here: