如何退出NSThread [英] How to exit NSThread

查看:111
本文介绍了如何退出NSThread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这样的线程,

I am using a thread like this,

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

线程正常运行,我想退出中间的线程,我该怎么做呢。如果我使用[NSThread退出]应用程序挂起。

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.

推荐答案

你在哪个线程中运行[NSThread exit]?
[NSThread exit]在当前线程中运行,因此您需要将其作为 myfunction 选择器的一部分进行调用。如果你在主线程中调用它,它将只退出主线程。

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 应该根据共享变量和协调线程退出。

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

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

您可以在协调线程和工作线程使用withObject。通过这种方式,协调线程可以更改共享对象中的实例变量,以便工作线程可以根据这种情况停止它的工作。

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.

退出工作线程协调线程只会调用smth:

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

[someObject setStillWorkToBeDone:false];

这篇关于如何退出NSThread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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