Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 466
Sonius Avatar asked Apr 29 '16 11:04

Sonius


2 Answers

Fastest way, but not the brightest (general problem):

from tkinter import *
import threading, time

def execute_script():
    def sub_execute():
        print("Wait 5 seconds")
        time.sleep(5)
        print("5 seconds passed by")
    threading.Thread(target=sub_execute).start()

root = Tk()
button_1 = Button(master=root, text="Execute Script", command=execute_script)
button_1.pack()
root.mainloop()
like image 134
João Avatar answered Oct 04 '22 05:10

João


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.

like image 25
Games Brainiac Avatar answered Oct 04 '22 05:10

Games Brainiac