GDC信号量错误

时间:2015-05-09 23:51:56

标签: ios multithreading semaphore gdc

构建以下Swift类以使用GDC模拟Java Thread sleepinterrupt方法。 sleep方法创建一个信号量,等待它发出信号并在睡眠过早结束时返回trueinterrupt方法通知信号量以使线程退出睡眠状态:

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

0 个答案:

没有答案