Created
October 23, 2018 22:40
-
-
Save mrnkr/a7d53a03bbe0fccc5bf97d7a4770f202 to your computer and use it in GitHub Desktop.
Peterson's algorithm for mutual exclusion
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 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