Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active May 16, 2017 15:51
Show Gist options
  • 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
}
}
@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