Skip to content

Instantly share code, notes, and snippets.

@mrnkr
Created October 23, 2018 22:40
Show Gist options
  • Save mrnkr/a7d53a03bbe0fccc5bf97d7a4770f202 to your computer and use it in GitHub Desktop.
Save mrnkr/a7d53a03bbe0fccc5bf97d7a4770f202 to your computer and use it in GitHub Desktop.
Peterson's algorithm for mutual exclusion
import UIKit
var n: Int = 0;
var favoredProcess: String = "first"
var processOneWantsIn: Bool = false
var processTwoWantsIn: Bool = false
func processOne(task: () -> Void) {
while n < 50 {
processOneWantsIn = true
favoredProcess = "second"
while processTwoWantsIn && favoredProcess == "second" {
print("Process one is waiting...")
}
task()
processOneWantsIn = false
}
}
func processTwo(task: () -> Void) {
while n < 50 {
processTwoWantsIn = true
favoredProcess = "first"
while processOneWantsIn && favoredProcess == "first" {
print("Process two is waiting...")
}
task()
processTwoWantsIn = false
}
}
DispatchQueue.global(qos: .userInitiated).async {
processOne {
let date = NSDate().timeIntervalSince1970
print("Process one is running at \(date)")
n = n + 1
}
}
DispatchQueue.global(qos: .userInitiated).async {
processTwo {
let date = NSDate().timeIntervalSince1970
print("Process two is running at \(date)")
n = n + 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment