我有一个启动 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/