Home > front end >  Is there any way to execute 2 infinite loops at the same time in python
Is there any way to execute 2 infinite loops at the same time in python

Time:07-02

im use speechrecognition, and tkinter, i have speech recognition in a inifinte loop, because i want them to recognize my voice all the time together with a GUI of tkinter, i need I need them to run in the same program since I want the gui to change along with the voice recognition but if anyone can give me another solution is welcome

CodePudding user response:

you can use multithreading, you can visit this link to find out how to do that.

https://www.geeksforgeeks.org/multithreading-python-set-1/

CodePudding user response:

Maybe Timers could work?

from threading import Timer
from time import sleep

x0 = 0
x1 = 0

def process1():
    global x0
    print(x0)
    x0 = x0   1
    Timer(0, process1, []).start()

def process2():
    global x1
    print(x1)
    x1 = x1 - 1
    Timer(0, process2, []).start()

Timer(0, process1, []).start()
Timer(0, process2, []).start()

In a similar fashion to javascript's setTimeout.

Eg instead of an infinite loop, you break your loop down into steps, and have it do a timer to do the next step, allowing the other "process" do its thing. This would behave like multithreading on a single thread.

  • Related