Objective C: How to kill a thread while in another thread in Objective-C?

6 Solutions Collect From Internet About “Objective C: How to kill a thread while in another thread in Objective-C?”

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.