Python:多线程下载器相互阻塞

标签 python multithreading

我有一个无限多线程下载器,它是这样工作的:

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/

相关文章:

python - 按整数访问行,按标签访问列 Pandas

python - Numba 和 KeyboardInterrupt 异常冲突

c# - 多线程,如果一个线程崩溃了应用程序会发生什么

c++ - 将互斥量与 shared_ptr 结合使用以保护跨拷贝共享的数据

java - 持续解析和处理文本

python - 函数返回指向带有结果的数组的指针。如何访问这些数据

python - 在函数python中传递带冒号的变量

python - Anaconda 3 Python 命令似乎已损坏

c - 在 Linux 上等待多个条件变量而没有不必要的 sleep ?

java - JavaFX-无法再次运行任务