Sonius Sonius - 7 months ago 40
Python Question

Python: threads can only be started once

I want to do threading in python. I have 100 words and want to put them in 6 different links. If one of the links is ready, I want that the link can get the new word. This while the other threads have still the first word in work. My complete program should be allowed to do more code first when the 100 keywords are done. I have the following code:

threads = []

def getresults(seed):
for link in links:
t = threading.Thread(target=getLinkResult, args = (suggestengine, seed))
threads.append(t)
for thread in threads:
thread.start()

for seed in tqdm:
getresults(seed + a)
getresults(seed + b)

for thread in threads:
thread.join()

#code that should happen after


I get an error at the moment:
threads can only be started once

Answer

You are calling getresults twice, and both times, they reference the same global threads list. This means, that when you call getresults for the first time, threads are started.

When you call them for the second time, the previous threads that are already running, have the .start() method invoked again.

You should start threads in the getresults as local threads, and then append them to the global threads list.

Although you can do the following:

for thread in threads:
    if not thread.is_alive():
        thread.start()

it does not solve the problem as one or more threads might've already ended and therefore be started again, and would therefore cause the same error.

Comments