Skip to content

Instantly share code, notes, and snippets.

@sergiomtzlosa
Created August 12, 2014 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergiomtzlosa/c10721eeab3ca2dd46d7 to your computer and use it in GitHub Desktop.
Save sergiomtzlosa/c10721eeab3ca2dd46d7 to your computer and use it in GitHub Desktop.
//
// SMSync.swift
// TableExample
//
// Created by sid on 11/08/14.
// Copyright (c) 2014 Sergio Martinez-Losa. All rights reserved.
//
import Foundation
/**
A semaphotre class that waits till async executions ends
example:
var request : HTTPRequest = HTTPRequest()
var callback2 : (() -> ()) = { () -> () in
// something for callback
SMSync.endSync()
}
SMSync.beginSync({() -> () in
request.method(callback);
})
*/
typealias Completion = (() -> ())
var semaphone : dispatch_semaphore_t!
class SMSync : NSObject
{
class func beginSync(completion : Completion)
{
semaphone = dispatch_semaphore_create(0)
completion();
while (dispatch_semaphore_wait(semaphone, DISPATCH_TIME_NOW) != 0)
{
NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow:0))
}
}
class func endSync()
{
SMSync.performSync(semaphone)
}
class func performInMainThreads(completion : Completion)
{
dispatch_async(dispatch_get_main_queue()) {
completion();
}
}
private class func performSync(sem : dispatch_semaphore_t)
{
dispatch_semaphore_signal(sem);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment