Last active
April 18, 2017 06:28
-
-
Save phlippieb/0ef9544834029ef1b58f184bbbd78f4e to your computer and use it in GitHub Desktop.
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
/* | |
For use in an XCode Playground | |
*/ | |
import Foundation | |
import XCPlayground | |
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true | |
// Method 1: Works | |
let nsLock = NSRecursiveLock() | |
func synch1(_ closure: () -> ()) { | |
nsLock.lock() | |
closure() | |
nsLock.unlock() | |
} | |
// Method 2: Doesn't work! | |
var mutex = pthread_mutex_t() | |
func synch2(_ closure: () -> ()) { | |
pthread_mutex_lock(&mutex) | |
defer { pthread_mutex_unlock(&mutex) } | |
return closure() | |
} | |
// Method 3: Works | |
let queue = DispatchQueue(label: "q") | |
func synch3(_ closure: () -> ()) { | |
queue.sync { | |
closure() | |
} | |
} | |
// Method 4: Works | |
let semaphore = DispatchSemaphore(value: 1) | |
func synch4(_ closure: () -> ()) { | |
semaphore.wait() | |
closure() | |
semaphore.signal() | |
} | |
func foo() { | |
// Prints a lhs bar, runs a somewhat time-consuming calculation, then prints a rhs bar. | |
// If calls to foo are properly synchronized, output will be alternating bars. | |
// If calls are not synchronized, two or more bars on the same side will be printed directly after one another. | |
print("-") | |
for i in 0 ... 9999 { | |
_ = i * i * i | |
} | |
print(" -") | |
} | |
for _ in 0 ..< 10 { | |
DispatchQueue.global(qos: .default).async { | |
synch1 { | |
foo() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment