Python multitherad hogyan?

Sziasztok!

Hogy lehet python 2-ben azt megoldani, egy szál folyamatosan olvassa a szenzor adatokat, és ha szükséges meghívjon egy függvényt? Problémám az, hogy a fő programban adatbekérés történik billentyűzet, vagy infrán akkor a szál is megáll, ha ezt kiveszem belőle, akkor miden ok. Próbáltam az adatbevitelt is külön szálakban, de akkor csak laggolt az egész.

Az ide vágó kódrészlet:
def distance():
global Dist
while Ok:
...
if Collision <> 0 and Dist <= Collision and Direction == 1:
control(" ")
def control(char):
global Servo, Direction, Speed, Ok, Wheel, Collision
....

def ctrl_keyb():
control(getch.getch())

def ctrl_ir():
control(lirc.nextcode()[0])

if __name__ == '__main__':
setup()
pwm.set_pwm(0, 0, Servo)

setSpeed(30)
stop()
Ok = True;
sockid = lirc.init("hnrbrtRpiCar",LircRC)

therad_distances = threading.Thread(target=distance)
therad_distances.start()
while Ok:
pass
ctrl_keyb()
# ctrl_ir()
print ("Direction:",direction_str[Direction+1],"-",Speed," Wheel:",wheel_str[Wheel+1]," - ",Servo," Collision: ",Collision," cm Distance: %.1f cm" % Dist)
(END)

Hozzászólások

a getch csomag nem igazán multi-thread (GIL) ready, ez az implementáció viszont igen:


import threading, time, sys

if sys.platform == 'win32':
    import msvcrt
    getch = msvcrt.getch
    getche = msvcrt.getche
else:
    import sys
    import termios
    def __gen_ch_getter(echo):
        def __fun():
            fd = sys.stdin.fileno()
            oldattr = termios.tcgetattr(fd)
            newattr = oldattr[:]
            try:
                if echo:
                    # disable ctrl character printing, otherwise, backspace will be printed as "^?"
                    lflag = ~(termios.ICANON | termios.ECHOCTL)
                else:
                    lflag = ~(termios.ICANON | termios.ECHO)
                newattr[3] &= lflag
                termios.tcsetattr(fd, termios.TCSADRAIN, newattr)
                ch = sys.stdin.read(1)
                if echo and ord(ch) == 127: # backspace
                    # emulate backspace erasing
                    # https://stackoverflow.com/a/47962872/404271
                    sys.stdout.write('\b \b')
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, oldattr)
            return ch
        return __fun
    getch = __gen_ch_getter(False)
    getche = __gen_ch_getter(True)

def printer():
    while 1:
        print(".")
        time.sleep(1)

def asker():
    while 1:
        char = getch()
        print("Pressed: %r" % char)


thread = threading.Thread(target=printer)
thread.daemon = True
thread.start()

asker()

Köszönöm mindenkinek, nem a Shared memory esetemben lett a megoldás.

Az utókornak:

#!/usr/bin/env python

import multiprocessing, time, getch

def f(n):
while 1:
print n.value

if __name__ == '__main__':
num = multiprocessing.Value('i', 0)

p = multiprocessing.Process(target=f, args=(num, ))
p.start()

while 1:
pass
char = getch.getch()
num.value=ord(char)

---
[hnrbrt - YT]