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

时间:2022-01-20 02:13:51

When using the thread library, Is there a way to join all threads that were created by start_new_threads ?

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

for example:

例如:

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,))

How can join all threads ?

如何加入所有线程?

1 个解决方案

#1


16  

Is there a reason you're using thread instead of the recommended Threading module? If not, you should rather use the threading.Thread objects which have a join method:

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

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()

#1


16  

Is there a reason you're using thread instead of the recommended Threading module? If not, you should rather use the threading.Thread objects which have a join method:

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

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()