Created
October 23, 2018 23:27
-
-
Save mrnkr/d7835c6dc3c50e04fc4421a9bb5c5677 to your computer and use it in GitHub Desktop.
Semaphores for solving the mutual exclusion problem
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 | |
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