Error with GDC semaphore

163 Views Asked by At

The following Swift class is built to emulate Java Thread sleep and interrupt methods with GDC. The sleep method creates a semaphore, waits for it to be signaled and returns true when sleep ended prematurely. The interrupt method signals the semaphore to get the thread out of sleep:

   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)
       }

}

As you can see, I put some objc_sync_enter and objc_sync_exit (though it's most probably redundant), but it didn't help: with iPhone 6 emulator it works great, but iPad Retina emulator gives BAD INSTRUCTION CODE on dispatch_semaphore_wait. Any suggestions?

0

There are 0 best solutions below