简体   繁体   English

如何在python多线程环境中限制函数执行时间?

[英]How to limit function execution time in python multithreading environment?

I have a script which runs quite a lot of concurrent threads (at least 200). 我有一个运行大量并发线程(至少200个)的脚本。 Every thread does some quite complex evaluations, which can take unpredictably lot of time. 每个线程都会执行一些非常复杂的评估,这可能会花费大量时间。 The evaluation method is implemented in C and I can't change it. 评估方法是用C实现的,我无法更改。 I want to limit the method execution time for every thread. 我想限制每个线程的方法执行时间。 Please advise. 请指教。

From what I understand of your problem, it might be a good case for using multiprocessing instead of multithreading. 据我对您的问题的了解,使用多处理而不是多线程可能是一个很好的案例。 Multiprocessing will allow you to make use of all the available resources on the system - and then some, if you're not careful. 多处理将允许您利用系统上的所有可用资源-如果您不小心,则可以利用其中的一些资源。

Threads don't actually run in parallel, so unless you're doing a lot of waiting for I/O or something like that, it would make more sense to call it from a separate process. 线程实际上并不会并行运行,因此除非您正在大量等待I / O或类似的操作,否则从单独的进程中调用它会更有意义。 You could use the Python multiprocessing library to call it from a Python script, or you could use a wrapper written in C and use some form of interprocess communication . 您可以使用Python多处理库从Python脚本中调用它,也可以使用用C编写的包装器并使用某种形式的进程间通信 The second option will avoid the overhead of launching another Python instance just to run some C code. 第二种选择将避免仅运行一些C代码而启动另一个Python实例的开销。

You could call time.sleep (or perform other tasks and check the system clock for elapsed time), and then check for results after the desired interval, permitting any processes that haven't finished to continue running while you make use of the results. 您可以调用time.sleep(或执行其他任务,并检查系统时钟是否经过了时间),然后在所需的时间间隔后检查结果,从而允许在使用结果时所有尚未完成的进程继续运行。 Or, if you don't care at that point, you can send a signal to kill the process. 或者,如果您当时不在乎,则可以发送信号终止该过程。

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

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