5

使用线程库时,有没有办法加入由 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,))

如何加入所有线程?

4

2 回答 2

24

您使用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()
于 2013-10-24T06:30:34.987 回答
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 要简单得多。希望有帮助。

于 2019-12-26T00:26:58.013 回答