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