How to exit NSThread

依然范特西╮ 提交于 2019-11-28 01:38:45

问题


I am using a thread like this,

[NSThread detachNewThreadSelector:@selector(myfunction) toTarget:self withObject

the thread is running correctly, I want to quit the thread in the middle,how can I do this.If I use [NSThread exit] the application is hanging.


回答1:


In which thread are you running "[NSThread exit]"? [NSThread exit] runs in the current thread so you need to call this as part of the myfunction selector. If you call it in the main thread, it will just exit the main thread.

Also, it's not a good idea to stop threads like this as it prevents the thread being exited from cleaning up resources.

myfunction should exit based on a shared variable with the coordinating thread.

- (void) myFunction
{
    while([someObject stillWorkToBeDone]) 
    { 
      performBitsOfWork();
    }
}

You can share a reference between the coordinating thread and the worker thread using "withObject". In this way, the coordinating thread could change an instance variable in the shared object so that the worker thread could stop it's work based on this condition.

To exit the worker thread the coordinating thread would just call smth like:

[someObject setStillWorkToBeDone:false];



回答2:


You should call

-[NSThread cancel]

on the thread you created and check for

-[NSThread isCancelled]

in your while loop.



来源:https://stackoverflow.com/questions/909283/how-to-exit-nsthread

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