Last active
May 16, 2017 15:51
-
-
Save JadenGeller/c0a97893d4a35a960289 to your computer and use it in GitHub Desktop.
Swift Semaphore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is now built into Swift 3. See https://developer.apple.com/reference/dispatch/dispatchsemaphore