Skip to content

Instantly share code, notes, and snippets.

@mrnkr
Created October 23, 2018 23:27
Show Gist options
  • Save mrnkr/d7835c6dc3c50e04fc4421a9bb5c5677 to your computer and use it in GitHub Desktop.
Save mrnkr/d7835c6dc3c50e04fc4421a9bb5c5677 to your computer and use it in GitHub Desktop.
Semaphores for solving the mutual exclusion problem
import UIKit
class Semaphore {
var n: Int
init(n: Int) {
self.n = n
}
func P() {
while self.n == 0 {}
self.n = self.n - 1
}
func V() {
self.n = self.n + 1
}
}
var s: Semaphore = Semaphore(n: 1)
var ran: Int = 0
func processOne(task: () -> Void) {
while ran < 50 {
s.P()
task()
s.V()
}
}
func processTwo(task: () -> Void) {
while (ran < 50) {
s.P()
task()
s.V()
}
}
DispatchQueue.global(qos: .userInitiated).async {
processOne {
let date = NSDate().timeIntervalSince1970
print("Process one ran at \(date)")
ran = ran + 1
}
}
DispatchQueue.global(qos: .userInitiated).async {
processTwo {
let date = NSDate().timeIntervalSince1970
print("Process two ran at \(date)")
ran = ran + 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment