How to limit execution time of a function call in Python

后端 未结 10 1897
遥遥无期
遥遥无期 2020-11-22 10:25

There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which

10条回答
  •  眼角桃花
    2020-11-22 11:08

    The only "safe" way to do this, in any language, is to use a secondary process to do that timeout-thing, otherwise you need to build your code in such a way that it will time out safely by itself, for instance by checking the time elapsed in a loop or similar. If changing the method isn't an option, a thread will not suffice.

    Why? Because you're risking leaving things in a bad state when you do. If the thread is simply killed mid-method, locks being held, etc. will just be held, and cannot be released.

    So look at the process way, do not look at the thread way.

提交回复
热议问题