My answer is: "Do not try to do this."
Of course, you are likely to find some kind of hack that seems to work in your particular case. But the race conditions here are very difficult to fix.
An obvious approach is to let thread A make a blocking call, and then set thread B to kill A if the timeout expires.
But ... What if the timeout expires while A returning from the blocking call? In particular, what if B thinks it's time to kill A , then the OS scheduler decides to start A for a while, then your OS decides to run code B that kills A ?
Bottom line: you end killing A at some vague point in its execution. (For example, perhaps he simply deducted $ 500 from a savings account, but has not yet added $ 500 to his current account. The possibilities are endless ...)
OK, so you can have thread A for the sole purpose of starting a library call, and then signal a condition or something else when it ends. At least this work can be done in principle. But even then, what if the library itself has some kind of internal state that remains in an inconsistent state, should A be killed at the wrong time?
There are good reasons why asynchronous thread cancellation was excluded from the C ++ 11 standard. Just say no. Correct the library procedure. No matter what it costs, it will almost certainly be cheaper in the long run than what you are trying.
source share