我有一个无限多线程下载器,它是这样工作的:
queue = Queue() # links for downloading
def downloader(queue):
while:
link = queue.get()
# do download with requests library
for i in range(4):
task = Thread(target=downloader, args=(queue,))
task.start()
队列会定期填充新数据。但是当我打印出下载了哪个链接时,线程似乎没有并行工作,例如:
time 0 - thread 1 - link 1
time 1 - thread 1 - link 2
time 2 - thread 1 - link 3
time 3 - thread 1 - link 4
time 4 - thread 2 - link 5
time 5 - thread 2 - link 6
time 6 - thread 2 - link 7
time 7 - thread 3 - link 8
time 8 - thread 3 - link 9
time 9 - thread 3 - link 10
time 10 - thread 1 - link 11
time 11 - thread 1 - link 12
我希望它会更像:thread 1 2 3 4 1 2 3 4. Server has 4 cpus.
谢谢
最佳答案
仔细检查您的输出文件以及每个线程写入的位置。写锁可能导致代码比预期更串行地执行。
关于Python:多线程下载器相互阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41564768/