使用线程库时, 有没有办法加入由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,))
如何加入所有主题?
答案 0 :(得分:21)
您是否有理由使用thread
而不是推荐的Threading模块?如果没有,您应该使用具有连接方法的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 :(得分:0)
如果要使用_thread而不是threading.Thread,则可以实现互斥锁来知道其他线程何时完成。
# make as many lock objects as you have threads ==> len(url_ip_hash.keys())
exitmutexes = [thread.allocate_lock() for _ in range of len(url_ip_hash.keys())]
def check_url(threadnum, url):
"enter your code here"""
exitmutexes[threadnum].acquire()
for url in url_ip_hash.keys():
thread.start_new_thread(check_url, (url,))
# the mutex's lock method can be used to check its state.
# continues in while loop until lock acquired for every exitmutex
for mutex in exitmutexes:
while not mutex.locked(): pass
print('Program exited successfully.')
另一种方法是创建一个全局布尔列表,为列表中的每个项目分配False,并在线程退出时将其切换为True。
exitstatus = [False] * len(url_ip_hash.keys)
def check_url(threadnum, url):
""" Enter your code here"""
exitstatus[threadnum] = True
for url in url_ip_hash.keys():
thread.start_new_thread(check_url, (threadnum, url))
while False in exitstatus: pass
print('Program exited successfully.')
正如您所见,如前所述,使用threading.Thread模块并执行.join要简单得多。希望有帮助。