Last active
June 4, 2016 21:37
-
-
Save janodev/9be703900c107e4fb3761b9665730b57 to your computer and use it in GitHub Desktop.
Mutex built on dispatch_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
import Foundation | |
// a mutex built on a semaphore | |
// see http://www.cocoawithlove.com/blog/2016/06/02/threads-and-mutexes.html | |
struct DispatchSemaphore { | |
let s = dispatch_semaphore_create(1) | |
func sync<R>(@noescape f: () throws -> R) rethrows -> R { | |
_ = dispatch_semaphore_wait(s, DISPATCH_TIME_FOREVER) | |
defer { _ = dispatch_semaphore_signal(s) } | |
return try f() | |
} | |
} | |
let semaphore = DispatchSemaphore() | |
// incement and print | |
var i: Int = 0 | |
var f = { i = i+1; print("\(i)") } | |
// repeat 10x asynchronously | |
let queue: dispatch_queue_t = dispatch_queue_create("com.blah.myqueue", DISPATCH_QUEUE_CONCURRENT) | |
for _ in 0..<10 { | |
dispatch_async(queue){ | |
true ? semaphore.sync(f) : f() // try false to disable the mutex | |
} | |
} | |
// wait 2 seconds | |
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate:NSDate(timeIntervalSinceNow:2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment