Skip to content

Instantly share code, notes, and snippets.

@mrnkr
Created October 24, 2018 18:52
Show Gist options
  • Save mrnkr/77d1018e3599296efe9b544215e2d7b0 to your computer and use it in GitHub Desktop.
Save mrnkr/77d1018e3599296efe9b544215e2d7b0 to your computer and use it in GitHub Desktop.
Philosophers problem solved with semaphores on swift
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 table = Semaphore(n: 4)
var chopsticks: [Semaphore] = []
var ran = 0
for _ in 1...5 {
chopsticks.append(Semaphore(n: 1))
}
func philosopher(n: Int) {
while ran < 50 {
table.P()
chopsticks[n].P()
chopsticks[n+1 % 5].P()
print("Philosopher #\(n+1) is eating :P")
ran = ran + 1
chopsticks[n].V()
chopsticks[n+1 % 5].V()
table.V()
}
}
for i in 0...4 {
DispatchQueue.global(qos: .userInitiated).async {
philosopher(n: i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment