Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sleep thread from another one

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.

like image 372
Broes De Cat Avatar asked Dec 09 '11 08:12

Broes De Cat


People also ask

Can sleep () method causes another thread to sleep?

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.

Does thread sleep block other threads?

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.

How do I make another thread sleep in Java?

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 .

What happens when a sleep is called on thread?

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.


1 Answers

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.

like image 51
James Kanze Avatar answered Oct 26 '22 23:10

James Kanze