我有一个简单的休息服务,允许您创建任务。当客户端请求任务时 - 它返回一个唯一的任务编号并开始在单独的线程中执行。最简单的实现方法
class Executor:
def __init__(self, max_workers=1):
self.executor = ThreadPoolExecutor(max_workers)
def execute(self, body, task_number):
# some logic
pass
def some_rest_method(request):
body = json.loads(request.body)
task_id = generate_task_id()
Executor(max_workers=1).execute(body)
return Response({'taskId': task_id})
如果我知道一个请求是一个新任务(新线程),那么每次使用一个(!)个工作线程创建 ThreadPoolExecutor 是一个好主意吗?也许值得以某种方式将它们放入队列中?也许最好的选择是每次都创建一个常规流?
最佳答案
Is it a good idea to create each time ThreadPoolExecutor...
没有。这完全违背了线程池的目的。使用线程池的原因是,您不会为每个请求创建和销毁新线程。创建和销毁线程的成本很高。线程池的想法是,它使“工作线程”保持事件状态,并为每个下一个请求重新使用它/它们。
...with just one thread
单线程执行器有一个很好的用例,尽管它可能不适用于您的问题。用例是,您需要“在后台”执行一系列任务,但您也需要按顺序执行它们。单线程执行器将按照提交的顺序一个接一个地执行任务。
Perhaps it is worth putting them in the queue somehow?
您已经将它们放入队列中。每个线程池都有一个待处理任务队列。当您提交任务(即executor.execute(...)
)时,会将任务放入队列中。
what's the best way...in my case?
简单服务器的骨架看起来像这样(伪代码):
POOL = ThreadPoolExecutor(...with however many threads seem appropriate...)
def service():
socket = create_a_socket_that_listens_on_whatever_port()
while True:
client_connection = socket.accept()
POOL.submit(request_handler, connection=connection)
def request_handler(connection):
request = receive_request_from(connection)
reply = generate_reply_based_on(request)
send_reply_to(reply, connection)
connection.close()
def main():
initialize_stuff()
service()
当然,还有很多细节我遗漏了。我无法为你设计。尤其是在 Python 中。我用其他语言编写过这样的服务器,但我对 Python 还很陌生。
关于python-3.x - 将 ThreadPoolExecutor 与一名工作人员一起使用是个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65148339/