如何在Kivy中实现多线程处理?

时间:2019-04-14 03:07:08

标签: python multithreading multiprocessing kivy

我正在尝试使用与kivy相符的基于numpy的功能,但是一旦将这些功能称为on_enter到Kivy Screen,应用程序将冻结,并消耗大量CPU和RAM。我怀疑是因为它们不能在一个线程进程中共存,所以我尝试了多线程,但该应用程序仍然崩溃。我已经被困了好几天了。

这些是我与Thread模块结合的numpy函数。

c=threading.Condition()
class Compare_Thread(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name=name
    def run(self):
        engine = pyttsx.init()
        count=1
        while (count>0):
            c.acquire()
            livecsv=np.genfromtxt("lettera.csv", delimiter=",", skip_header=1, filling_values=np.nan, dtype=int, case_sensitive=True, deletechars='', replace_space=' ')
            refcsv=np.genfromtxt("refcsv1.csv", delimiter=",", skip_header=1, filling_values=np.nan, dtype=int, case_sensitive=True, deletechars='', replace_space=' ')
            A=np.array(livecsv)
            B=np.array(refcsv)
            D=B - A[-1]
            match= B[np.abs(D).sum(axis=1).argmin()]
            global where
            where=match[0]
            time.sleep(1)
            count = count + 1
            c.notify_all()

class Verify_Thread(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name=name
    def run(self):
        global where
        engine = pyttsx.init()           
        num2words = {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', \
         6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J', \
        11: 'K', 12: 'L', 13: 'M', 14: 'N', \
        15: 'O', 16: 'P', 17: 'Q', 18: 'R', \
        19: 'S', 20: 'T', 21: 'U', 22: 'V', 23: 'W', 24: 'X', 25: 'Y', 26: 'Z', \
        31: 'Hello', 32: 'Goodbye', 33: 'Good Morning', 34: 'Good Night', 35: 'Good Afternoon', \
        90: 'Ninety', 0: 'Zero'}
        text2speech=num2words[where]
        engine.say(text2speech)
        engine.runAndWait()

这是我尝试在其中调用这些函数的屏幕,但是使整个应用程序崩溃了。

class LetterAScreen(Screen):
    def on_enter(self):
        self.loader()
    def loader(self):
        lol= Identifier()
        self.identity()
        self.verifier()
    def identity(self):
        global where
        t1=Compare_Thread("thread1")
        t1.daemon=True
        t1.start()
        t1.join() 
    def verifier(self):
        global where
        count = 1
        while (count>0 and where!=1):
            self.identity()
            count=count+1
        t2=Compare_Thread("thread2")
        t2.start()
        t2.join()

我不知道我的代码是否错误,或者是否是Kivy中的错误,或者我是否需要实现线程/多处理。请帮助我。

0 个答案:

没有答案