Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pause/resume a thread

How can I pause/resume a thread? Once I Join() a thread, I can't restart it. So how can I start a thread and make it pause whenever the button 'pause' is pressed, and resume it when resume button is pressed?

The only thing this thread does, is show some random text in a label control.

like image 380
Yustme Avatar asked May 06 '12 10:05

Yustme


People also ask

How do I pause a current 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 .

How do I write a resume for a thread?

Java Thread resume() methodThe resume() method of thread class is only used with suspend() method. This method is used to resume a thread which was suspended using suspend() method. This method allows the suspended thread to start again.

How do you pause a thread in C++?

You can pause a thread by making it wait on a std::mutex .

How do you pause a thread in Python?

You can suspend the calling thread for a given time in Python using the sleep method from the time module. It accepts the number of seconds for which you want to put the calling thread on suspension for.


1 Answers

Maybe the ManualResetEvent is a good choice. A short example:

private static EventWaitHandle waitHandle = new ManualResetEvent(initialState: true); 

// Main thread
public void OnPauseClick(...) {
   waitHandle.Reset();
}

public void OnResumeClick(...) {
   waitHandle.Set();
}

// Worker thread
public void DoSth() {
   while (true) {
     // show some random text in a label control (btw. you have to
     // dispatch the action onto the main thread)
     waitHandle.WaitOne(); // waits for the signal to be set
   }
}
like image 84
Johannes Egger Avatar answered Oct 20 '22 03:10

Johannes Egger