Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Options for informing a Thread to stop

I need to inform a so-called worker thread to stop work at the next available oppertunity. Currently I'm using something like this:

    public void Run()
    {
        while (!StopRequested)
            DoWork();
    }

The concern I have is that StopRequested is being set to True on a different thread. Is this safe? I know I can't lock a boolean. Perhaps there's a different way to inform a thread that a stop is required. For example I would be happy to check Thread.CurrentThread.ThreadState == ThreadState.StopRequested but it's not clear how I can set the thread state as such.

like image 974
Ralph Shillington Avatar asked Jul 30 '09 18:07

Ralph Shillington


People also ask

How do I stop another thread?

Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.

Can a thread cancel another thread?

A thread automatically terminates when it returns from its entry-point routine. A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.

Is thread sleep blocking?

The problem : Thread. sleep – it blocks the thread. This makes it unusable until it resumes, preventing us from running 2 tasks concurrently. Fortunately, there are solutions, which we'll discuss next.

When we start execution of Java application then JVM starts how many threads?

The JVM only starts 1 user thread, also called the "Main" thread.


1 Answers

This is a better approach than trying to set the ThreadState. If you look at the docs for ThreadState, it specifically says that StopRequested is for internal use only.

Setting a boolean from another thread is a safe operation. You shouldn't need to lock in this case.

like image 134
Reed Copsey Avatar answered Oct 11 '22 18:10

Reed Copsey