Is it possible in VB.NET to suspend and resume processes?
I would like to entirely pause a process or an external thread.
Warning: .Suspend() has been depreciated. The reason is suspending another thread is not even remotely safe.
Lets say somewhere on a lower level, there is a thread performing some important operation like writing bytes, now you go ahead and suspend the thread before it finishes what happens to that range of bytes? It will likely be paused until you Resume() which can lead to damaging results.
with that said:
Thread.Sleep(Time in ms)
will pause the current thread for x amount of milliseconds.
If you are looking to Suspend the current thread then
Thread.CurrentThread.Suspend()
and to resume the current thread
Thread.CurrentThread.Resume()
You will need to import the namespace to use this code as is.
Imports System.Threading
or change it to
System.Threading.Thread.CurrentThread.Suspend()
Be careful and if your not Multi-Threading and handling your own threads, I don't recommend it. There is a reason why MS depreciated the code. Keep that in mind.
This is the right way to do what (I think) you need.
You have to call ResumeThread() and SuspendThread() (API functions) on all the threads of target process...
Related
Let's say we have a job A and a job B (not kotlin's Job, just some kind of work).
I am told that coroutines can suspend and thus the underlying thread used by A will not be blocked and can be used for B, while A suspends.
Let's say, that A performs some kind of downloading data from server. How does A perform such work, while being suspended (if it gets suspended)? How does it know that it is time to resume and hold the thread again? How the thread deal with the coroutines states and decides, which one to run?
I guess it uses good old wait/notify mechanism under the hood, however it is unclear for me, how the example download can happen while the thread is used for another work already?
How does the coroutine perform work, while being suspended (if it gets suspended)?
After some research I found out, that when the coroutine suspends it actually gets dispatched to another thread (as was mentioned by bylazy), in which it continues execution.
How does it know that it is time to resume and hold the thread again?
Taking the example from the question, the download will be dispatched to a separate thread of the implicit threadpool (which was mentioned by Tenfour04) and will use continuation object to resume on former thread.
At the same time, the former thread remains available for another work. Whereas Java's Thread has differences that explain why coroutines' performance is higher:
Thread is a different mechanism, which is linked to the native thread of OS. This is the reason why creating hundreds/thousands of threads is impossible - thread consumes a lot of OS' memory. Coroutine is a user-level abstraction of some worker which does not use excessive amount of memory, since it is not linked to native resources and use resources of JVM heap.
Thread gets blocked instead of suspending and dispatching the job to another thread.
Thread cannot be used until its work completes.
Thread is asynchrounous whereas coroutines are sequentional. According to the previous point, a thread performs some kind of work asyncrhonously and cannot be used. On the other hand a coroutine, being a user-friendly abstraction, is executed on the thread and after it gets suspended, the next one gets executed on the same thread. (This point answers to "How the thread deal with the coroutines states and decides, which one to run?")
So the coroutines make the better and more efficient use of threads, taking care of dispatching, reusing resources, managing thread pool and etc.
The sources I used:
Coroutines vs Threads (Educba)
Difference between a thread and a coroutine in Kotlin
I do many asynchronous execution with blocks in my application.
But I need to kill all the threads which they are not the main thread if a certain event appears in my application.
So is it possible to stop the execution of all blocks ? Or in other terms, kill all the threads which they are not the main thread ?
PS : I tried to execute blocks inside NSOperationQueue, but my first operation does not start at the good time while the followings does.
If you need to kill threads to cancel operations, you’re probably doing it wrong. NSOperationQueue or similar solution (like implementing cancellation logic in your blocks) is IMHO the right way to go. If you have some problems with the operation queue, try to sort it out, don’t avoid the problem by creating a worse one.
How can I kill a thread created by performSelectorInBackground:withObject: from the main thread? I need to force termination of freezing threads.
You cannot kill background threads from the main thread, the method that is executing in a background thread has to return for the thread to end.
Your actual problem seems to be that your background thread is freezing, you should solve that instead of trying to work around it.
I'm not sure if this may help but here goes:
Assuming you're calling that performSelector call from class A. And assuming that class A is about to be released from memory in class B (which is where if the selector hasn't been performed yet, you might be getting a crash - Hence you're posting this question on SO):
Wherever you're releasing A from B, do this:
[NSObject cancelPreviousPerformRequestsWithTarget:A];
Apple documentation says
The recommended way to exit a thread is to let it exit its entry point
routine normally. Although Cocoa, POSIX, and Multiprocessing Services
offer routines for killing threads directly, the use of such routines
is strongly discouraged. Killing a thread prevents that thread from
cleaning up after itself. Memory allocated by the thread could
potentially be leaked and any other resources currently in use by the
thread might not be cleaned up properly, creating potential problems
later.
I was trying to set up a multi thread app. One of the threads is working as background to get some data transfer. Right now this thread automatically kill itself after it's job done.
Somehow I need to kill this thread in another thread in order stop its job immediately. Are there any api or method for making this happen?
In short, you can't. Or, more precisely, you should not. Not ever and not under any circumstances.
There is absolutely no way for thread A to know the exact state of thread B when A kills B. If B is holding any locks or in the middle of a system call or calling into a system framework when A kills it, then the resulting state of your application is going to be nondeterministic.
Actually -- it will be somewhat deterministic in that you are pretty much guaranteed that a crash will happen sometime in the near future.
If you need to terminate thread B, you need to do so in a controlled fashion. The most common way is to have a cancel flag or method that can be set/called. thread B then needs to periodically check this flag or check to see if the method has been called, clean up whatever it is doing, and then exit.
That is, you are going to have to modify the logic in thread B to support this.
bbum is correct, you don't want to simply kill a thread. You can more safely kill a process, because it is isolated from the rest of the system. Because a thread shares memory and resources with the rest of the process, killing it would likely lead to all sorts of problems.
So, what are you supposed to do?
The only correct way of handling this is to have a way for your main thread to send a message to the worker thread telling it to quit. The worker thread must check for this message periodically and voluntarily quit.
An easy way to do this is with a flag, a boolean variable accessible by both threads. If you have multiple worker threads, you might need something more sophisticated, though.
Isn't that a bad idea? (If the other thread is in the middle of doing something in a critical section, it could leave stuff in an inconsistent state.) Couldn't you just set some shared flag variable, and have the other thread check it periodically to see if it should stop?
One thing you could do would be pass messages between the front thread and the background thread, potentially using something like this to facilitate message passing.
If you are using pthread then you try with 'pthread_kill' , I had tried long back it did not worked for me, basically if the thread is in some blocking call it won't work.
It is true that killing a thread is not good option, if you are looking for some kind for fix for some issue then you can try with this.
In my personal view it is best to let a thread run its course naturally. It's difficult to make guarantees about the effect of trying to kill a thread.
I have some code like this:
doDatabaseFetch {
...
#synchronized(self) {
...
}
}
and many objects that call doDatabaseFetch as the user uses the view.
My problem is, I have an operation (navigate to the next view) that also requires a database fetch. My problem is that it hits the same synchronize block and waits it's turn! I would ideally like this operation to kill all the threads waiting or give this thread a higher priority so that it can execute immediately.
Apple says that
The recommended way to exit a thread is to let it exit its entry point routine normally. Although Cocoa, POSIX, and Multiprocessing Services offer routines for killing threads directly, the use of such routines is strongly discouraged.
So I don't think I should kill the threads... but how can I let them exit normally if they're waiting on a synchronized block? Will I have to write my own semaphore to handle this behavior?
Thanks!
Nick.
The first question to ask here - do you need that big of a critical section so many threads are waiting to enter? What you are doing here is serializing parallel execution, i.e. making your program single-threaded again (but slower.) Reduce the lock scope as much as possible, think about reducing contention at the application level, use appropriate synchronization tools (wait/signal) - you'll find that you don't need to kill threads, pretty much ever. I know it's a very general advise, but it really helps to think that way.
Typically you cannot terminate a thread that is waiting on a synchronized block, if you need that sort of behavior, you should be using a timed wait and signal paradigm so that threads are sound asleep waiting and can be interrupted. Plus if you use a timed wait and signal paradigm, each time the timed wait expires your threads have the opportunity to not go back to sleep but rather to exit or take some other path (ie. even if you don't choose to terminate them).
Synchronized blocks are designed for uncontested locks, on an uncontested lock, the synchronization should be pretty close to a noop, but as soon as the lock becomes contested they have a very detrimental to application performance, moreso than even simply because they are serializing your parallel program.
I'm not an Objective C expert by any means, but I'm sure that there are some more advanced synchronization patterns such as barriers, conditions, atomics, etc.