I am working with a library that has a blocking call that never times out if it does not succeed. I would like to be able to handle this error condition more gracefully. I know there must be a way to wrap the call in a worker thread (or some other type of delegate object), wait x amount of seconds, and then throw an exception if x amount of seconds have passed. I only need to do this for one function in the library. How do I go about implementing this? I see similar examples all over the net but none that are doing exactly what I’m trying to do. Thanks!
Share
My answer is “do not attempt to do this”.
Sure, you can probably find some hack that will appear to work in your particular case. But the race conditions here are very hard to fix.
The obvious approach is to have thread
Amake the blocking call, then set up threadBto killAif a timeout expires.But… What if the timeout expires at the same time
Ais returning from the blocking call? Specifically, what ifBthinks it is time to killA, then your OS scheduler decides to runAfor a while, then your OS decides to run theBcode that killsA?Bottom line: You wind up killing
Aat some indeterminate point in its execution. (For example, maybe it just deducted $500 from the savings account but has not yet added $500 to the checking account. The possibilities are endless…)OK, so you can have thread
Aexist for the sole purpose of running the library call, and then signal a condition or whatever when it finishes. At least it is possible to make this work in principle. But even then, what if the library itself has some internal state that gets left in an inconsistent state shouldAget killed at an inopportune moment?There are good reasons asynchronous thread cancellation was omitted from the C++11 standard. Just say no. Fix the library routine. Whatever that costs, it is almost certainly cheaper in the long run than what you are attempting.