Skip to content

Instantly share code, notes, and snippets.

@macu
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save macu/3e7ba383a813f1c7ac52 to your computer and use it in GitHub Desktop.

Select an option

Save macu/3e7ba383a813f1c7ac52 to your computer and use it in GitHub Desktop.
Simple utility for executing synchronous code in concurrent read/write blocks. Thanks to "Mastering Grand Central Dispatch" from WWDC 2011: https://developer.apple.com/videos/wwdc/2011/?id=210
/// RWSync provides methods for executing read/write blocks through the Grand Central Dispatch.
/// Multiple reads may execute concurrently, but a write will block all other executions in the queue.
class RWSync {
private let queue: dispatch_queue_t
/// Instantiates RWSync with a new concurrent queue.
init() {
let queueName = "rwsync.\(mach_absolute_time())"
self.queue = dispatch_queue_create(queueName, DISPATCH_QUEUE_CONCURRENT)
}
func readAsync(cb: () -> ()) {
dispatch_async(queue, cb)
}
func readAsyncMain(cb: () -> ()) {
dispatch_async(queue) {
dispatch_sync(dispatch_get_main_queue(), cb)
}
}
func writeAsync(cb: () -> ()) {
dispatch_barrier_async(queue, cb)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment