构建以下 Swift 类以使用 GDC模拟 Java 线程sleep
和方法。interrupt
该sleep
方法创建一个信号量,等待它发出信号并true
在睡眠过早结束时返回。该interrupt
方法向信号量发出信号以使线程脱离睡眠状态:
public protocol GDCRunnable {
func run()
}
public class GDCThread {
private var semaphore : dispatch_semaphore_t?;
private let queue : dispatch_queue_t;
private let runnable : GDCRunnable?;
public init(_priority :Int = DISPATCH_QUEUE_PRIORITY_DEFAULT,
runnable : GDCRunnable? ) {
self.runnable = runnable
queue = dispatch_get_global_queue(_priority, 0)
}
public func start() {
dispatch_async(queue) {
self.run();
}
}
public func run() {
if runnable != nil {runnable!.run()}
}
public func sleep(_timeoutMillis : Int) -> Bool {
objc_sync_enter(self)
semaphore = dispatch_semaphore_create(1)
objc_sync_exit(self)
let signaled = (dispatch_semaphore_wait(semaphore,
dispatch_time(DISPATCH_TIME_NOW, Int64(_timeoutMillis*1000000))) != 0)
if !signaled {
dispatch_semaphore_signal(semaphore);
}
objc_sync_enter(self)
semaphore = nil;
objc_sync_exit(self)
return signaled
}
public func interrupt () {
objc_sync_enter(self)
if let currentSemaphore = semaphore {
dispatch_semaphore_signal(currentSemaphore)
}
objc_sync_exit(self)
}
}
正如你所看到的,我放了一些 objc_sync_enter
and objc_sync_exit
(虽然它很可能是多余的),但它没有帮助:使用 iPhone 6 模拟器它工作得很好,但是 iPad Retina 模拟器在dispatch_semaphore_wait
. 有什么建议么?