Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active May 16, 2017 15:51
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save JadenGeller/c0a97893d4a35a960289 to your computer and use it in GitHub Desktop.
Save JadenGeller/c0a97893d4a35a960289 to your computer and use it in GitHub Desktop.
Swift Semaphore
struct Semaphore {
let semaphore: dispatch_semaphore_t
init(value: Int = 0) {
semaphore = dispatch_semaphore_create(value)
}
// Blocks the thread until the semaphore is free and returns true
// or until the timeout passes and returns false
func wait(nanosecondTimeout: Int64) -> Bool {
return dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, nanosecondTimeout)) != 0
}
// Blocks the thread until the semaphore is free
func wait() {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
// Alerts the semaphore that it is no longer being held by the current thread
// and returns a boolean indicating whether another thread was woken
func signal() -> Bool {
return dispatch_semaphore_signal(semaphore) != 0
}
}
@dimohamdy
Copy link

how can i use it

@gustavohansen
Copy link

@dimohamdy

let semaphore = Semaphore(value: 0);

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in

//your code 
 semaphore.signal();

}

semaphore.wait();

@dlo
Copy link

dlo commented Dec 5, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment