How to kill a Thread with Objective C?

柔情痞子 提交于 2019-12-01 07:42:26

问题


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.)

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?

Cheers

MrMage


回答1:


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.

As the very page you linked to says:

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.



来源:https://stackoverflow.com/questions/1351976/how-to-kill-a-thread-with-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!