Given two threads A and B, is there any portable way that A can suspend B, without any custom code in B for that purpose?
Rationale: currently, B is a very complicated algorithm, which should cleanly exit when A (a monitoring thread) tells it to, by checking some shared flag from time to time. The problem is that for debugging purposes I would like to know exactly in which state B is the moment A requests such an exit (e.g. to see where we forgot to check the shared flag), so I would like to pause B (for debugging) from A. In other words, I need to not only synchronize the threads, but synchronize debugging the threads.
Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t. sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.
Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution. One thread cannot call Thread. Sleep on another thread.
Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can't be negative, else it throws IllegalArgumentException .
Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.
It depends on the system. Windows has a function SuspendThread
, but I'll admit that I don't know much about it. Under Unix, you should be able to send a signal to the thread using pthread_kill
(which despite its name, doesn't kill the thread, but just sends a signal), and catch it in the targeted thread, where the signal handler can call sleep
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With