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,))
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()
# 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.')
您使用
thread
而不是推荐的Threading模块是有原因的吗?如果不是,则应该使用具有join方法的threading.Thread
对象:如果要使用线程而不是threading.thread,则可以实现互斥量以了解其他线程何时完成。
另一种方法是创建一个全局布尔列表,为列表中的每个项指定False,并在线程退出时将它们切换为True。
如您所见,如前所述,使用threading.Thread模块并执行.join要简单得多。希望能有所帮助。
相关问题 更多 >
编程相关推荐