-
-
Save boudhayan/21ae22df10f6e7381b6f6c67b3cb495e to your computer and use it in GitHub Desktop.
Swift Semaphore
This file contains hidden or 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