简体   繁体   English

长时间运行的进程上的 ThreadPoolExecutor

[英]ThreadPoolExecutor on long running process

I want to use ThreadPoolExecutor on a webapp (django),我想在 webapp (django) 上使用 ThreadPoolExecutor,

All examples that I saw are using the thread pool like that:我看到的所有示例都使用这样的线程池:

with ThreadPoolExecutor(max_workers=1) as executor: code I tried to store the thread pool as a class member of a class and to use map fucntion with ThreadPoolExecutor(max_workers=1) as executor: code我试图将线程池存储为 class 的 class 成员并使用map

but I got memory leak, the only way I could use it is by the with notation但我得到了 memory 泄漏,我可以使用它的唯一方法是使用with符号

so I have 2 questions:所以我有两个问题:

  1. Each time I run with ThreadPoolExecutor does it creates threads again and then release them, in other word is this operation is expensive?每次我with ThreadPoolExecutor运行时,它是否会再次创建线程然后释放它们,换句话说,这个操作是否很昂贵?

  2. If I avoid using with how can I release the memory of the threads如果我避免使用with如何释放线程的 memory

thanks谢谢

Normally, web applications are stateless.通常,web 应用程序是无状态的。 That means every object you create should live in a request and die at the end of the request.这意味着您创建的每个 object 都应该存在于请求中并在请求结束时终止。 That includes your ThreadPoolExecutor .这包括您的ThreadPoolExecutor Having an executor at the application level may work, but it will be embedded into your web application instead of running as a separate group of processes.在应用程序级别有一个执行程序可能会起作用,但它将嵌入到您的 web 应用程序中,而不是作为单独的一组进程运行。

So if you want to take the workers down or restart them, your web app will have to restart as well.因此,如果您想关闭或重新启动工作人员,您的 web 应用程序也必须重新启动。

And there will be stability concerns, since there is no main process watching over child processes detecting which one has gotten stale, so requires a lot of code to get multiprocessing right.并且会有稳定性问题,因为没有主进程监视子进程来检测哪个已经过时,因此需要大量代码才能正确进行多处理。

Alternatively, If you want a persistent group of processes to listen to a job queue and run your tasks, there are several projects that do that for you.或者,如果您想要一组持久的进程来监听作业队列并运行您的任务,那么几个项目可以为您做到这一点。 All you need to do is to set up a server that takes care of queueing and locking such as redis or rabbitmq, then point your project at that server and start the workers.您需要做的就是设置一个负责排队和锁定的服务器,例如 redis 或 rabbitmq,然后将您的项目指向该服务器并启动工作程序。 Some projects even let you use the database as a job queue backend.有些项目甚至允许您将数据库用作作业队列后端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM