Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if a Thread object is overwritten when the thread is not yet finished?

Suppose you have a class where you start some background thread: this class could have a Run() method that starts up these threads, and a Stop() method that stops them properly. Some of these background threads may have been created manually, others may be managed by a Timer, which is activated when the above Run() method is invoked.

public void Run()
{
    m_ShutdownRequested = false; // shutdown flag disabled

    m_WorkerThread = new Thread(Work) { IsBackground = true };
    m_WorkerThread.Start();
    // ...
}

public void Stop()
{
    lock (m_LockInput)
    {
        m_ShutdownRequested = true; // shutdown flag enabled
        Monitor.Pulse(m_LockInput);
    }
    m_WorkerThread.Join(m_ShutdownTimeout);
}

Suppose that the Run() method is invoked when the user clicks the Run button on the UI. Similarly, the Stop() method is invoked when the user clicks the Stop button on the UI. How should these methods be implemented in order to be invoked via the UI? Should they both be asynchronous? If yes, how to deal with the possibility that some thread can not stop?

Suppose that after executing the Stop() method, some threads were not stopped. At this point, if the user click the Run button again, the instance of that class would have some threads not yet stopped. However, starting the Run() method, the previous m_WorkerThread instance is overwritten: what happens if this overwriting is performed when the thread is not yet finished?

like image 381
enzom83 Avatar asked Sep 07 '25 19:09

enzom83


1 Answers

The thread saunters along, unaffected. You, on the other hand, just lost any way to address it.

like image 147
spender Avatar answered Sep 09 '25 07:09

spender