Skip to content

Instantly share code, notes, and snippets.

@mrnkr
Created October 24, 2018 21:14
Show Gist options
  • Save mrnkr/8ddba79c33708a5cd3034bbee29bf00d to your computer and use it in GitHub Desktop.
Save mrnkr/8ddba79c33708a5cd3034bbee29bf00d to your computer and use it in GitHub Desktop.
Semaphores implemented using monitors and condition variables
import UIKit
class Condition {
var waiting: Bool
init() {
waiting = false
}
func wait() {
waiting = true
while waiting {}
}
func signal() {
waiting = false
}
}
class SemaphoreMonitor {
var busy: Bool
var free: Condition
init() {
busy = false
free = Condition()
}
func P() {
if busy {
free.wait()
}
busy = true
}
func V() {
busy = false
free.signal()
}
}
var s = SemaphoreMonitor()
var ran = 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