Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a safe way to stop a running thread?

I have a thread which contains execution of an IronPython script. For some reason I may need to stop this thread at any time, including script execution. How to achieve this? The first idea is Thread.Abort(), but it's known to be evil...

like image 350
aplavin Avatar asked Feb 14 '12 05:02

aplavin


People also ask

How do I stop a running thread in Linux?

You can use pthread_cancel() to kill a thread: int pthread_cancel(pthread_t thread); Note that the thread might not get a chance to do necessary cleanups, for example, release a lock, free memory and so on..

How can threads be stopped or blocked?

Blocking a Thread: These methods cause the thread to go into the blocked (or not-runnable) state. The thread will return to the runnable state when the specified time is elapsed in the case of sleep( ), the resume() method is invoked in the case of suspend( ), and the notify( ) method is called in the case of wait().

Which method is used to stop thread for some time?

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 .


1 Answers

What is a safe way to stop a running thread?

Put the thread in its own process. When you want it to stop, kill the process.

That is the only safe way to kill a thread. Aborting a thread can severely destabilize a process and lose user data. There's no way to avoid the "lose user data" scenario if you really, truly need to be able to kill a thread that could be doing anything. The only way to avoid destabilizing the process that is calling for the abort is to make them different processes entirely.

like image 151
Eric Lippert Avatar answered Oct 05 '22 03:10

Eric Lippert