gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:59 31 4
gpt4 key购买 nike

在我的代码中,我需要在 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com