Reputation: 356
I'm trying to start different threads inside a python script.
class MyThread (threading.Thread):
def __init__(self, sf):
threading.Thread.__init__(self)
self.sf = sf
def run (self):
# opening files
I append the different threads to a threadlist
while True:
path_to_file = L.pop()
tr = MyThread(path_to_file)
tr.start()
threadlist.append(tr)
for elem in threadlist:
print(elem._name)
print(elem.isAlive())
answer = input("Another thread to start? ")
if answer is not 'y':
break
Printing out the alive state of every thread shows that the previously started ones get stopped:
Thread-1
True
Another thread to start? y
Thread-1
False
Thread-2
True
Another thread to start? y
Thread-1
False
Thread-2
False
Thread-3
True
What am I doing wrong here?
Upvotes: 0
Views: 169
Reputation: 75629
I cannot tell why your threads are stopped, because you have not shown what is in your run
method.
As others have mentioned, it is not clear why you are extending the Thread
class.
However, here is one working example of how you might make the class above exhibit multiple living threads. Bear in mind that threading in Python will not buy you CPU parallelism, because of the Global Interpreter Lock. However, as noted in the comment below, it can buy you performance if your application is IO-bound.
from threading import Thread
import time
class MyThread (Thread):
def __init__(self):
Thread.__init__(self)
def run (self):
time.sleep(1)
# opening files
threadlist = []
for i in range(3):
tr = MyThread()
tr.start()
threadlist.append(tr)
for elem in threadlist:
print(elem.isAlive())
Upvotes: 1