How can i stop the background thread from the main thread in Iphone NSthread?

笑着哭i 提交于 2019-12-07 11:27:28

In my experience, its usually best to let a thread exit gracefully by itself. How about having some common variable that the main thread could set to false if things go awry. The second thread could periodically check this variable and if it has been set to false, it knows it should clean up and return.

I think you could use condition variables in a more elegant fashion, but his approach with the proper use of NSLock should work.

NSThread implements a method -(void)cancel that sets state information in the receiving thread to indicate, it should exit. The receiving background thread should - if behaving properly - regulary check whether it is cancelled using -(BOOL)isCancelled.

This way the receiver has a chance to clean up it's acquired resources in a proper way.

Looking into the Java language thread semantic, this apparatus works quite the same way. Javas Thread implements two methods void Thread.interrupt() and boolean Thread.isInterrupted().

In case long running background operations do not react to an attempt to -cancel them, i would see this as an serious problem and file a bug report / change request.

You may wait on the termination of the background thread by regulary calling either -(BOOL)isFinished or -(BOOL)isExecuting on the background NSThread. Unfortunately the NSDidBecomeSingleThreadedNotification is not supported on the iPhone plattform.

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