How can I create multiple running threads?
There is no multi-process, nor multi-threading, support on the Arduino. You can do something close to multiple threads with some software though.
You want to look at Protothreads:
Protothreads are extremely lightweight stackless threads designed for severely memory constrained systems, such as small embedded systems or wireless sensor network nodes. Protothreads provide linear code execution for event-driven systems implemented in C. Protothreads can be used with or without an underlying operating system to provide blocking event-handlers. Protothreads provide sequential flow of control without complex state machines or full multi-threading.
Of course, there is an Arduino example here with example code. This SO question might be useful, too.
ArduinoThread is a good one too.
AVR based Arduino's do not support (hardware) threading, I am unfamiliar with the ARM based Arduino's. One way around this limitation is the use of interrupts, especially timed interrupts. You can program a timer to interrupt the main routine every so many microseconds, to run a specific other routine.
http://arduino.cc/en/Reference/Interrupts
It is possible to do software side multi-threading on the Uno. Hardware level threading is not supported.
To achieve multithreading, it will require the implementation of a basic scheduler and maintaining a process or task list to track the different tasks that need to be run.
The structure of a very simple non-preemptive scheduler would be like:
//Pseudocode
void loop()
{
for(i=o; i<n; i++)
run(tasklist[i] for timelimit):
}
Here, tasklist
can be an array of function pointers.
tasklist [] = {function1, function2, function3, ...}
With each function of the form:
int function1(long time_available)
{
top:
//Do short task
if (run_time<time_available)
goto top;
}
Each function can perform a separate task such as function1
performing LED manipulations, and function2
doing float calculations. It will be the responsibility of each task(function) to adhere to the time allocated to it.
Hopefully, this should be enough to get you started.