维护线程列表并通过ID终止它们

huangapple go评论106阅读模式
英文:

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

  1. 不要停止线程,只停止报告工作已完成。这取决于您的规范,但假设从API中看不到结果会"足够好",您可以之后找出如何进行优化。

  2. 根据您的线程正在执行的任务,可能可以使用queue.Queuethreading.Event或类似的方式添加状态检查。如果状态发生变化,可以更改线程行为,可能会提前返回。

无论是否将request id : thread id的映射保留是个好主意,这取决于您希望如何解决问题。我认为没有简单的方法通过线程id获取线程,所以最好保留一个request id : thread objectrequest id : synchronization object的映射,比如之前提到的EventQueue

英文:

You have a few choices here.

  1. 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.
  2. Depending on what your thread is doing, it may be easy to add a status check with queue.Queue or threading.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.

huangapple
  • 本文由 发表于 2023年6月15日 03:19:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476896.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定