How to implement timeout for function in c++

后端 未结 3 1361
不思量自难忘°
不思量自难忘° 2020-12-01 13:10

I have got function f; I want to throw exception 1s after start f. I can\'t modify f(). It it possible to do it in c++?

try {
   f();
}
catch (TimeoutExcepti         


        
3条回答
  •  情书的邮戳
    2020-12-01 13:30

    You can create a new thread and asynchronously wait for 1s to pass, and then throw an exception. However, exceptions can only be caught in the same thread where they're thrown, so, you cannot catch in the same thread where you called f(), like in your example code - but that's not a stated requirement, so it may be OK for you.

    Only if f is guaranteed to return in less than 1s, can you do this synchronously:

    • store current time
    • call f()
    • wait for current time - stored time + 1s

    But it may be quite difficult to prove that f in fact does return in time.

提交回复
热议问题