python - Python 中的多处理 : Handle Multiple Worker Threads

标签 python python-3.x multithreading python-multiprocessing

在我的代码中,我需要在 python 程序中运行多个工作线程实例。我最初创建了几个工作线程实例(比如 10 个),然后将它们添加到池中。每当客户端请求服务时,就应该调用并为客户端保留一个线程。完成任务后,线程应添加回池中。

到目前为止我已经编写了以下代码。但我不确定如何在池中永远运行线程(它们应该在池内休眠),在需要时调用并获取服务,并在处理后将它们添加回池中(应该再次休眠)。任何帮助将不胜感激。

PRED = Queue(10)

class Worker(threading.Thread):
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID  =threadID
        self.name = name

    def run(self):
        print("starting " + self.name + " thread")
        while True:
            ??
        print("Exiting " + self.name + " thread")


def work():
    print("working")
    time.sleep(3)
  • 假设工作线程位于 PRED 队列中。
  • work() 是我应该调用来为客户提供服务的方法。

最佳答案

这是我从 Python 文档中得出的内容

read more: https://docs.python.org/3/library/queue.html#queue.Queue.join

确保您充分阅读了它,其中有一些很酷的选项,例如创建优先级队列或先进先出或后进先出。

import queue
import threading
import time


# The queue for tasks
q = queue.Queue()


# Worker, handles each task
def worker():
    while True:
        item = q.get()
        if item is None:
            break
        print("Working on", item)
        time.sleep(1)
        q.task_done()


def start_workers(worker_pool=1000):
    threads = []
    for i in range(worker_pool):
        t = threading.Thread(target=worker)
        t.start()
        threads.append(t)
    return threads


def stop_workers(threads):
    # stop workers
    for i in threads:
        q.put(None)
    for t in threads:
        t.join()


def create_queue(task_items):
    for item in task_items:
        q.put(item)


if __name__ == "__main__":
    # Dummy tasks
    tasks = [item for item in range(1000)]

    # Start up your workers
    workers = start_workers(worker_pool=10)
    create_queue(tasks)

    # Blocks until all tasks are complete
    q.join()

    stop_workers(workers)

关于python - Python 中的多处理 : Handle Multiple Worker Threads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55545964/

相关文章:

java - JFrame 立即关闭

c# - Java 线程创建性能 vs C# 线程创建性能 vs C++( native 线程)?

python - `pip install psutil` 正在抛出 `error: Unsupported architecture` 。任何解决方法?

python - 使用 Sympy 分离实部和虚部

python - PyQt5在两个类之间传递参数: lambda vs partial

python-3.x - 如何使用python3中的搜索从主字符串的空格前后获取子字符串?

python - (Pygame) 鼠标悬停检测的问题

python - 文本未动态显示,pygame

python-3.x - 使用 PIL 和 SKIMAGE 打开 PGM 文件时出错

java - 从线程更新进度条时,SWT 窗口变得无响应