Kill hanging function in Python in multithreaded e

2019-06-27 04:51发布

问题:

I would like to kill a function that executes to long. What is important this function is inside C extension (wrapped in Cython), and I would like this solution to work in multithreaded enviorment. Since it is wrapped in Cython this thread could hold GIL.

I have no control whatsoever on what is happening inside this extension (and I think that this code will not respond to interrupts).

I'm fairly certain that this code will be only run on Unix machines. But question Python kill hanging function does not apply because I think that signals would not work in multithreaded enviorment (AFAIK it is undefined which thread will catch them) --- but I might be wrong on this one :) so correct me.

Is there any way for me to resolve this without spawning new processes.

回答1:

My solution is to wrap this function in another python process and if needed kill that process.

A piece of advice for anyone who googles this question: since process startup time (starting interpreter, loading modules and then loading data into memory) can last couple of seconds you need to group your function calls so this overhead won;t kill you (so there is no reusable solution really).

Example solution, was posted to na another question: How to interrupt native extension code without killing the interpreter?.