python - 在start_new_thread之后加入所有线程

gal*_*gal 5 python multithreading

使用线程库时,有没有办法连接start_new_threads创建的所有线程?

例如:

try:    
    import thread 
except ImportError:
    import _thread as thread #Py3K changed it.

for url in url_ip_hash.keys(): 
    thread.start_new_thread(check_url, (url,))
Run Code Online (Sandbox Code Playgroud)

如何加入所有线程?

Bas*_*hur 21

您是否有理由使用thread而不是推荐的线程模块?如果没有,您应该使用threading.Thread具有join方法的对象:

from threading import Thread


def check_url(url):
    # some code

threads = []
for url in url_ip_hash.keys():
    t = Thread(target=check_url, args=(url, ))
    t.start()
    threads.append(t)

# join all threads
for t in threads:
    t.join()
Run Code Online (Sandbox Code Playgroud)