Craigjw,
Is there any benefit to using multiprocessing over threads on this board, as the processor is single core, I can't see that there would be any advantage as either would be processed serially.
Let's assume that we only want multiple cores so that we can run multiple threads at the same time and get better performance.
Then why do we need threads at all?
Let's say that in my Python code I want to flash a LED. I might have a loop like this:
Code: Select all
def blink():
while True:
GPIO.output(LedPin, GPIO.HIGH) # led on
time.sleep(1)
GPIO.output(LedPin, GPIO.LOW) # led off
time.sleep(1)
Then let's say I wanted to get some user input from the keyboard, to change the flash rate for example, that requires a loop like this:
Code: Select all
def userInput():
while True:
name = input("Command? ")
# Do something with user input
Oops... that does not work. When "input" is waiting there is no way to run the blink loop. When "sleep" is sleeping there is no way to read the user input.
What to do?
Oh yes, introduce threads, so that both of those loops can run at the same time.
Code: Select all
import thread
import time
# Define a function for the LED flashing thread
def blink():
while True:
GPIO.output(LedPin, GPIO.HIGH) # led on
time.sleep(1)
GPIO.output(LedPin, GPIO.LOW) # led off
time.sleep(1)
# Define a function for the LED flashing thread
def userInput():
while True:
name = input("Command? ")
# Do something with user input
# Create two threads as follows
try:
thread.start_new_thread( blink, ("Thread-1", 2, ) )
thread.start_new_thread( userInput, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
while 1:
pass
Great, now my LED flashes at the same time the LED blinks. (Sorry if that code is not totally correct. I'm no Python user.)
Now, as W.H.Heydt says, these threads are ultimately juggled around by the Linux kernel. It does not matter if there is one core or many. The program will look the same. Unless you really need performance that is.
Of course this threading business is silly. There is a lot of complexity, inefficiency and overhead in there.
For example in Javascript under node.js the same could be done with something like this:
Code: Select all
var ledState = 0;
setInterval (function () {
gpio.write(pinNumber, ledState)
ledState = (ledState + 1) % 2
}, 1000)
var stdio = require('stdio');
stdio.question('Command?', function (err, input) {
// Do whatever you want with "input"
});
Which I think you might agree is much shorter and nicer.
Memory in C++ is a leaky abstraction .