Running infinite loops using threads in python

As far as I understood your question, you have two different tasks that you want them to perform continuously. Now regarding your questions:

how do I go about running two infinite loops?

You can create two different threads that will run these infinite loops for you. The first thread will perform your task1 and second one will perform task2.

Also, once I start executing a thread, how do I execute the other
thread when the first thread is running continuously/infinitely?

If you are using two different threads then you don’t need to be worried about this issue. If the threads are not sharing any resource then you don’t need to worry about this fact.
How ever if you want to stop/pause one thread from the other thread or vice versa then you can implement a mechanism using flags or locks. These questions will help in this case:

Is there any way to kill a Thread in Python?

Why does the python threading.Thread object has ‘start’, but not ‘stop’?

making-a-program-munltithreaded

Sample example using threading:

from threading import Thread

class myClassA(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start()
    def run(self):
        while True:
            print 'A'

class myClassB(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start()
    def run(self):
        while True:
            print 'B'


myClassA()
myClassB()
while True:
    pass

For shared resources?

Use Locks for them. Here are some examples. One, two and How to synchronize threads in python?

what if I don’t want to run it using classes? How do I do this using only methods?

from threading import Thread

def runA():
    while True:
        print 'A\n'

def runB():
    while True:
        print 'B\n'

if __name__ == "__main__":
    t1 = Thread(target = runA)
    t2 = Thread(target = runB)
    t1.setDaemon(True)
    t2.setDaemon(True)
    t1.start()
    t2.start()
    while True:
        pass

Leave a Comment