Running Infinite Loops Using Threads in Python

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

How to run infinite loops within threading in python

For the first example:

if __name__ == "__main__":
t1 = threading.Thread(target=thread1)
t2 = threading.Thread(target=thread2)

t1.start()
t2.start()

t1.join()
t2.join()

Pass the function, not the result of calling the function, to threading.Thread as its target.

For the section example. Don't call run. Call start. After creating an instance.

from threading import Thread
class Thread1(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True

def run():
while True:
print ("abc")

class Thread2(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True

def run():
while True:
print ("123")

Thread1().start()
Thread2().start()

Python: threading multiple infinite loops at the same time

The first Thread isn't starting. You are calling the func in main and attempting to set its return value as target, but it runs forever and the first Thread never gets created. You want:

from threading import Thread

def func(argument):
while True:
print(argument)

def main():
Thread(target=func,args=("1",)).start()
Thread(target=func,args=("2",)).start()
Thread(target=func,args=("3",)).start()
Thread(target=func,args=("4",)).start()

if __name__ == '__main__':
main()

This will pass func as an object. Starting the thread will call that object with the tuple of args specified.

python using a thread in an infinite loop

You have to start your thread like you did it in your code.
The important thing is to wait for the thread to complete (even if it infinite loop) because without it, you program will stop immediatly.
Just use

t.join()

And you code will run until t thread is over. If you want two thread, just do like this

t1.start()
t2.start()

t1.join()
t2.join()

And your two thread will run simultanously

For your crash problem, with multithreading, you have to look at Mutex for the IOerror

How to stop threads running infinite loops in python?

Your basic method does work, but you've still not posted enough code to show the flaw. I added a few lines of code to make it runnable and produced a result like:

$ python3 test.py
thread alive
main alive
thread alive
main alive
^CSignal caught
main alive
thread alive
main alive
main alive
main alive
^CSignal caught
^CSignal caught
main alive
^Z
[2]+ Stopped python3 test.py
$ kill %2

The problem demonstrated above involves the signal handler telling all the threads to exit, except the main thread, which still runs and still catches interrupts. The full source of this variant of the sample snippet is:

import threading, signal, time

def sighandler(signal,frame):
BaseThreadClass.stop_flag = True
print("Signal caught")

class BaseThreadClass(threading.Thread):
stop_flag = False
def __init__(self):
threading.Thread.__init__(self)
def run(self,*args):
while True:
if True:
time.sleep(1)
print("thread alive")
else:
#do computation and stuff
pass
if BaseThreadClass.stop_flag:
#do cleanup
break

signal.signal(signal.SIGINT, sighandler)

t = BaseThreadClass()
t.start()

while True:
time.sleep(1)
print("main alive")

The problem here is that the main thread never checks for the quit condition. But as you never posted what the main thread does, nor how the signal handler is activated, or information regarding whether threads may go a long time without checking the quit condition... I still don't know what went wrong in your program. The signal example shown in the library documentation raises an exception in order to divert the main thread.

Signals are a rather low level concept for this task, however. I took the liberty of writing a somewhat more naïve version of the main thread:

try:
t = BaseThreadClass()
t.start()
while True:
time.sleep(1)
print("main alive")
except KeyboardInterrupt:
BaseThreadClass.stop_flag = True
t.join()

This version catches the exception thrown by the default interrupt handler, signals the thread to stop, and waits for it to do so. It might even be appropriate to change the except clause to a finally, since we could want to clean the threads up on other errors too.



Related Topics



Leave a reply



Submit