Reputation: 5444
In java calls that wait on things, time, IO, semphores, etc will throw an "InterruptedException" when the thread waiting for the operation to complete is "interrupted".
Apparently the "SIGNAL"mechanism used by Pthreads in Linux, std::thread etc is a bit screwed up and difficult to manage.
I basically want to implement a way to abort mutex and semaphore waits, waiting joins etc from an "interrupt" ( kill or whatever ) call to a thread from another thread and catch via exception or return value that fact that this was done inside the thread being "interrupted", without effecting any other running thread.
Upvotes: 0
Views: 950
Reputation: 6983
Short answer: you can't; the only way you can do this is to perform your wait asynchronously.
Longer answer: Conceptually, if a thread could force exceptions to be thrown as an interrupt in other threads, they could do this at any time; not just during your wait or join or io.
It is not always safe to throw an exception - for example in a destructor - since if the stack is already being unwound because of an exception, trying to throw another exception will result in trying to handle 2 exceptions at once - which causes problems. This is true in Java so shouldn't be an unfamiliar concept.
Java and C# are not C++; their thread object does not represent by requirement a native thread; as such everything they do is likely already asynchronous under the hood to prevent thread starvation in the cases where the number of threads allowed is less than the number of thread objects.
This difference is very notable in the thread::abort style methods; which are fine in C# and Java, but very dangerous in C++ since it terminates the thread immediately in C++ whatever it is doing, including being in the middle of new() which may be locking a mutex - causing all further calls to new() in your application to deadlock.
Upvotes: 5