Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to wake a sleeping thread?

Is there a way to wake a sleeping thread in C#? So, have it sleep for either a long time and wake it when you want work processed?

like image 323
spig Avatar asked Aug 11 '10 15:08

spig


People also ask

How do you wake up a sleeping thread?

We can wake the thread by calling either the notify() or notifyAll() methods on the monitor that is being waited on. Use notifyAll() instead of notify() when you want to wake all threads that are in the waiting state.

How do you wake up a sleeping thread python?

The answer is to create a condition object and use its wait() method with the optional timeout instead of time. sleep(). If the thread needs to be woken prior to the timeout, call the notify() method of the condition object.

What happens when thread sleeps?

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.

What happens when a sleeping thread is interrupted?

In Java Threads, if any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException.


1 Answers

An AutoResetEvent object (or another WaitHandle implementation) can be used to sleep until a signal from another thread is received:

// launch a calculation thread
var waitHandle = new AutoResetEvent(false);
int result;
var calculationThread = new Thread(
    delegate
    {
        // this code will run on the calculation thread
        result = FactorSomeLargeNumber();
        waitHandle.Set();
    });
calculationThread.Start();

// now that the other thread is launched, we can do something else.
DoOtherStuff();

// we've run out of other stuff to do, so sleep until calculation thread finishes
waitHandle.WaitOne();
like image 163
Wim Coenen Avatar answered Sep 29 '22 22:09

Wim Coenen