构建以下Swift类以使用GDC模拟Java Thread 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
和objc_sync_exit
(虽然它很可能是多余的),但它没有帮助:iPhone 6
模拟器它工作得很好,但iPad Retina模拟器在dispatch_semaphore_wait
上给出了不良指令代码。有什么建议吗?