目标C:如何在Objective-C的另一个线程中杀死一个线程? [英] Objective C: How to kill a thread while in another thread in Objective-C?

查看:139
本文介绍了目标C:如何在Objective-C的另一个线程中杀死一个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立一个多线程应用程序.线程之一正在作为后台进行一些数据传输.现在,此线程在完成工作后会自动杀死自己. 我不知何故需要杀死另一个线程中的该线程,以便立即停止其工作.有没有实现此目的的API或方法?

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.

当A杀死B时,线程A绝对没有办法知道线程B的确切状态.如果B持有任何锁,或者在A杀死B时处于系统调用中间或正在调用系统框架,那么应用程序的最终状态将是不确定的.

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.

如果需要终止线程B,则需要以受控方式进行.最常见的方法是具有cancel标志或可以设置/调用的方法.然后,线程B需要定期检查此标志或检查是否已调用该方法,清除正在执行的操作,然后退出.

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.

也就是说,您将不得不修改线程B中的逻辑以支持此操作.

That is, you are going to have to modify the logic in thread B to support this.

这篇关于目标C:如何在Objective-C的另一个线程中杀死一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆