Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
834 views
in Technique[技术] by (71.8m points)

iphone - How to exit NSThread

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...