英文:
Maintaining list of threads and killing them by id
问题
我有一个Python网络应用程序,用户发送请求需要进行一些后台工作,我为每个请求启动一个新线程并立即向用户返回一个请求ID。线程大约需要5分钟完成其任务,并将结果添加到数据库中。
在某些情况下,我会收到一个带有先前请求的请求ID的停止请求,我应该如何停止为该请求ID启动的线程?维护一个请求ID|线程的字典并在以后使用该字典来停止特定线程是否是一个好主意?
英文:
I have a python webapp where users send a request which needs to do some background work, I launch a new thread for each request and return a request id to user immediately. Thread does it's task for about 5 minutes, and adds result to db.
In some conditions I receive a stop request with request id for a previous request, how should I stop the thread I had started for that request id ? Is Is it a good idea to maintain a dict of request_id|thread on request and later use dict to stop that particular thread ?
答案1
得分: 1
-
不要停止线程,只停止报告工作已完成。这取决于您的规范,但假设从API中看不到结果会"足够好",您可以之后找出如何进行优化。
-
根据您的线程正在执行的任务,可能可以使用
queue.Queue
或threading.Event
或类似的方式添加状态检查。如果状态发生变化,可以更改线程行为,可能会提前返回。
无论是否将request id : thread id
的映射保留是个好主意,这取决于您希望如何解决问题。我认为没有简单的方法通过线程id获取线程,所以最好保留一个request id : thread object
或request id : synchronization object
的映射,比如之前提到的Event
或Queue
。
英文:
You have a few choices here.
- Don't stop the thread, just stop reporting the work as done. This goes into what your spec is, but presumably the results not being visible from the API would be "good enough" and you can figure out how to optimize later.
- Depending on what your thread is doing, it may be easy to add a status check with
queue.Queue
orthreading.Event
or something similar. If you get a status change, change behavior in the thread, potentially returning early.
Whether or not it is a good idea to keep a mapping of request id : thread id
depends on how you want to address the problem. I don't think there's an easy way to get a thread by it's id, so it's probably best to keep a mapping of request id : thread object
or request id : synchronization object
such as the Event
or Queue
mentioned before.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论