如何解决如何在Python中完成线程的工作直到线程完成?
我是多线程的新手,在python中编写了代码,该函数创建了一个从列表中弹出元素然后下载的代码,我正在使用线程来下载多个文件。问题是线程在下载完全完成之前就死了并且代码结束了。(下载不完整的文件):
这是线程代码(下载功能运行良好,只有线程有问题):
for i in range(0,6):
time.sleep(10)
name = list.pop(0)
_thread.start_new_thread(func_download,(name,bucket_name,list,repo_name))
time.sleep(10)
解决方法
如果这是实际任务,请尽可能避免手动进行线程处理。
对于您的特定情况,ThreadPoolExecutor.map
完全可以满足您的需求。
如果您需要更精细的控制-请看queues,这是更好的同步元素。
,您的主线程必须等待其他线程完成。这并不难。为此,您使用join()
方法。
threads=[] #list to keep an eye on the threads
for i in range(0,6):
time.sleep(10)
name = list.pop(0)
thread=_thread.start_new_thread(func_download,(name,bucket_name,list,repo_name))
threads.append(thread)#add thread to the list
for thread in threads:
#only move on when this thread finished
thread.join()
#only when all threads finished you will get here
现在,仅在所有线程完成后,程序才应该继续。
,我已经知道需要什么:
``` for i in range(0,5):
time.sleep(5)
name = list.pop(0)
print("This is threading") # this print was testing purposes
thread = threading.Thread(target=function_name,args=(name,repo_name))
print(thread)
print("Now starting")
thread.start()
print("Waiting")
thread.join()
time.sleep(5)```
基本上使用join()时,我们将使用“ threading.Thread”而不是“ _thread.start_new_thread”
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。