I have a multithread program where one of the functions I'm running is overlapping itself. Here's an example:
import threading
def numbers(num):
for i in range(0, num):
print(i)
def main():
threading.Thread(target=numbers, args=[1000]).start()
while True:
threading.Thread(target=main).start()
I want this to run until the user quit for example.
In this example I want it to print all the numbers from 0 to num (0 to 1000) but it prints something like this:
5
2
3
1
2
0
3
4
5
16
4
0
7
1
2850
1
6
7292
8
6
3
9
10
40
1
237
5
6
10
8
9
1111
03
4
3
As I see it it's starting the thread even if it's already running so it's overlapping itself.
My question is if there is a way to not start a thread if it's already running so it will print 0 to 1000 and then starts again from 0 to 1000 repeatedly, but keep it as a thread so the rest of the program will continue running while it is counting?
CodePudding user response:
Check is_alive property to start a thread only if previous one has finished running.
import threading
def numbers(num):
for i in range(0, num):
print(i)
current_thread = None
while True:
if current_thread is None or not current_thread.is_alive():
current_thread = threading.Thread(target=numbers, args=[100])
current_thread.start()
# do something else
CodePudding user response:
Everytime you call threading.Thread(target=main).start()
a new Thread will be created and will be started. If you want to wait until the thread ends, you must use .join
as follows:
t = threading.Thread(target=main).start()
t.join()
This, inside the while True
will create infinite threads, but waiting for one to the other to finish.