python-在启动新线程后连接所有线程

2024-05-29 02:10:35 发布

您现在位置:Python中文网/ 问答频道 /正文

使用线程库时, 是否有方法连接所有由start_new_线程创建的线程?

例如:

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

如何连接所有线程?


Tags: 方法importurlnewforasit线程
2条回答

您使用thread而不是推荐的Threading模块是有原因的吗?如果不是,则应该使用具有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()

如果要使用线程而不是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要简单得多。希望能有所帮助。

相关问题 更多 >

    热门问题