python - 执行线程 5 by 5

标签 python multithreading

我有一个巨大的信息列表,我的程序应该分析其中的每一个。为了加快速度,我想使用线程,但我想将它们限制为 5 个。所以我需要用 5 个线程进行循环,当一个线程完成其工作时,获取一个新线程,直到列表末尾。 但我不知道该怎么做。我应该使用队列吗?现在我只是以最简单的方式运行 5 个线程: 谢谢!

for thread_number in range (5):
    thread = Th(thread_number)
    thread.start()

最佳答案

将工作线程和任务的思想分开——不要让一个工作线程处理一项任务,然后终止线程。相反,生成 5 个线程,并让它们都从公共(public)队列获取任务。让他们各自迭代,直到他们从队列中收到告诉他们退出的哨兵。

这比在线程完成一项任务后不断生成和终止线程更有效。

import logging
import Queue
import threading
logger = logging.getLogger(__name__)
N = 100
sentinel = object()

def worker(jobs):
    name = threading.current_thread().name
    for task in iter(jobs.get, sentinel):
        logger.info(task)
    logger.info('Done')


def main():
    logging.basicConfig(level=logging.DEBUG,
                            format='[%(asctime)s %(threadName)s] %(message)s',
                            datefmt='%H:%M:%S')

    jobs = Queue.Queue()
    # put tasks in the jobs Queue
    for task in range(N):
        jobs.put(task)

    threads = [threading.Thread(target=worker, args=(jobs,))
               for thread_number in range (5)]
    for t in threads:
        t.start()
        jobs.put(sentinel)     # Send a sentinel to terminate worker
    for t in threads:
        t.join()

if __name__ == '__main__':
    main()

关于python - 执行线程 5 by 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17345565/

相关文章:

Python从函数返回列表

python - Python 内置 pow 和大整数的数学 pow 之间的区别

c# - LINQ : Sequence contains no elements 错误

c++ - 在C++中对while循环进行多线程

javascript - 在 javascript 中使用 python 输出

python - 需要从一个txt文件读入字典

python - 如何在 webpy 中提供文件?

java - Android 健壮的线程架构?异步任务与线程/处理程序与服务/线程

c# - SyncRoot 模式有什么用?

java - 线程中断与 JNI 函数调用