0

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?

cyanide
  • 3,885
  • 3
  • 25
  • 33
  • What results do you get on iPhone 5 and iPad Air simulators? Thinking it could be 64-bit related. – Zev Eisenberg May 10 '15 at 03:14
  • Thank you, Zev. With IPad Air it works OK, with iPhone 5 doesn't. According to app tech spec, iPad Air and iPhone 6 have 64 bit architecture, iPhone 5 is 32bit device, so you are probably right. Is there a way to create a 32bit app with Xcode 6 ? – cyanide May 10 '15 at 11:58
  • Yes, but it’s better to get it working for both, especially because at some point 32 bit will no longer be supported. Unfortunately I don’t know enough about GCD semaphores or Swift to know what’s going on here. – Zev Eisenberg May 10 '15 at 13:01

0 Answers0