I have a need to add a timeout to a long running thread. We’re having some external issues which can sometimes cause that thread to hang at a certain line of code indefinitely. To make our process more robust, we would like to detect that the thread is no longer actively running/polling and abort the thread. This would let us clean up the resources and restart the thread.
What would be the preferred method of adding this functionality?
You need two things:
In the simplest version your suspect thread updates a shared static variable with the current time with a reliable frequency. How that fits into the control flow of your thread is up to you (This is the hard part – you would normally do that sort of thing with, ahem, another thread). Then just have a second thread wake up and check it every so often. If it’s not a recent time, abort the thread.