如何杀死一个线程与目标C? [英] How to kill a Thread with Objective C?

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

问题描述

我有一个第三方C ++库的调用,我把它放到自己的线程(目前使用NSThread)。我想给用户停止执行那个线程的能力。 (我很清楚这可能会导致的所有问题,但我仍然希望这样做。)

I have a call to a third-party C++ library which I have put into its own thread (currently using NSThread). I would like to give the user the ability to stop the execution of that thread. (I am well aware of all the problems this might cause, but I still wish to do so.)

根据苹果的线程编程指南,有可能在Cocoa这样做。对于iPhone来说,这是真的吗,还是我必须依靠Posix线程来完成我的目标?

According to Apple's Thread Programming Guide, there are possibilities in Cocoa to do so. Is this true for the iPhone, too, or do I have to rely on Posix threads to accomplish my goal?

干杯

MrMage

推荐答案

停止线程执行的正确方法是很好地停止执行。

The correct way to stop your thread executing is to ask it nicely to stop executing. Then, in your thread, you listen for such requests and obey them at an appropriate time.

你链接的页面说:


虽然Cocoa,POSIX和Multiprocessing Services提供了直接杀死线程的例程,但强烈建议不要使用这样的例程。杀死线程可以防止线程本身清理。线程分配的内存可能会被泄露,线程当前正在使用的任何其他资源可能无法正常清除,从而在以后产生潜在问题。

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.

如果您预期需要在一个操作的中间终止一个线程,你应该从一开始就设计你的线程来响应一个取消或退出消息。对于长期运行的操作,这可能意味着定期停止工作,并检查这样的消息是否到达。如果一个消息要求线程退出,线程将有机会执行任何所需的清理并正常退出;否则,它可以简单地返回工作并处理下一个数据块。

If you anticipate the need to terminate a thread in the middle of an operation, you should design your threads from the outset to respond to a cancel or exit message. For long-running operations, this might mean stopping work periodically and checking to see if such a message arrived. If a message does come in asking the thread to exit, the thread would then have the opportunity to perform any needed cleanup and exit gracefully; otherwise, it could simply go back to work and process the next chunk of data.

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

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