Skip to content

Instantly share code, notes, and snippets.

@boudhayan
Forked from JadenGeller/Semaphore.swift
Created February 8, 2017 06:48
Show Gist options
  • Select an option

  • Save boudhayan/21ae22df10f6e7381b6f6c67b3cb495e to your computer and use it in GitHub Desktop.

Select an option

Save boudhayan/21ae22df10f6e7381b6f6c67b3cb495e 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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment