ios - 如何快速取消多个线程之一

标签 ios iphone multithreading swift

我有一个启动 3 个异步线程的函数。每个线程做一些需要一些时间的事情。当某个线程首先完成时,我需要它来停止其他 2 个线程,但我(还)不知道该怎么做。

我的代码:

    class SomeController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    threads();
}

func threads(){
    
    let operationQueue = NSOperationQueue();

    operationQueue.addOperationWithBlock(
        {
            let thread = NSThread.currentThread();
            let threadNumber = thread.valueForKeyPath("private.seqNum").integerValue;
            NSThread.sleepForTimeInterval(30);
            
            println("Task #1 completed on thread #\(threadNumber)");
            
    })
    
    operationQueue.addOperationWithBlock(
        {
            let thread = NSThread.currentThread();
            let threadNumber = thread.valueForKeyPath("private.seqNum").integerValue;
            
            NSThread.sleepForTimeInterval(20);
            println("Task #2 completed on thread #\(threadNumber)");
            
    })
    
    operationQueue.addOperationWithBlock(
        {
            let thread = NSThread.currentThread();
            let threadNumber = thread.valueForKeyPath("private.seqNum").integerValue;
            
            NSThread.sleepForTimeInterval(5);
            println("Task #3 completed on thread #\(threadNumber)");
    })
}}

最佳答案

这实际上不是关于取消 NSThread 的问题。相反,这是一个如何取消 NSOperation 的问题。在这种情况下,取消所有操作相对容易,因为您创建一个 NSOperationQueue 的唯一目的是执行您的三个 block 。只需向 operationQueue 发送一条 cancelAllOperations 消息:

operationQueue.cancelAllOperations()

不幸的是操作取消是真正合作的,所以在操作中你必须定期检查 isCancelled 并根据需要终止:

var operation3:NSOperation?
operation3 = operationQueue.addOperationWithBlock {
    let thread = NSThread.currentThread()
    let threadNumber = thread.valueForKeyPath("private.seqNum").integerValue
    var timeout = 5

    while timeout-- > 0 && !operation3.isCancelled {
        NSThread.sleepForTimeInterval(1)
    }

    println("Task #3 completed on thread #\(threadNumber)")

    operationQueue.cancelAllOperations()
}

关于ios - 如何快速取消多个线程之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25850867/

相关文章:

iphone - COCOS2D中的ccc4颜色列表

iOS 7 m4a 到 mp3 编码 - 这可能吗?

Java多线程仅在第一个完成时调用其他

java - 如何保证Java线程运行在不同的内核上

java - 如果一个程序完全由线程安全类组成,那么它是线程安全程序吗?

iphone - 如何在提交到应用商店之前预见应用程序的原始大小

javascript - IOS WKWebView 和 UIWebView 没有加载 JavaScript 注册表单,而 Safari 可以

iphone - 添加 .a 文件后体系结构 armv7 的 undefined symbol

iphone - 实例变量访问(通过 self)导致空指针取消引用

iphone - 不使用 superview alpha 值更新 subview