我正在使用threading
进行并行下载,现在我有一个url_列表img_list
我想在两个线程中下载它,以便定义两个下载
我把一半放在download1
里,另一半放在download2
里,这样它会加快完成速度,但最后当我运行脚本时,我的下载仍然是串行的,我不知道为什么,我如何修改我的脚本
代码如下:
import requests,threading
img_list=[...]
num=len(img_list)
def download_1(img_list):
n=0
for i in img_list:
n+=1
with open('./img/'+str(n)+'.jpg','wb')as f:
f.write(requests.get(i).content)
print(str(n)+"download1 complete")
def download_2(img_list):
n=len(img_list)
for i in img_list:
n+=1
with open('./img/'+str(n)+'.jpg','wb')as f:
f.write(requests.get(i).content)
print(str(n)+"download2 complete")
thread_1 = threading.Thread(target=download_1(img_list[:int(num/2)]))
thread_2 = threading.Thread(target=download_2(img_list[int(num/2):]))
thread_1.start()
thread_2.start()
在这一行
调用
download_1(...)
并将结果(null)传递给线程。这就是它连续运行的原因。相反,您希望将download_1
函数本身(而不是调用它的结果)传递给线程。像这样:在两个地方都做
旁注:您应该在末尾
t.join()
两个线程您正在创建线程时调用这两个函数。因此,线程被传递为null,因此不执行任何操作。您应该像这样更改代码:
相关问题 更多 >
编程相关推荐