Created
October 24, 2018 21:14
-
-
Save mrnkr/8ddba79c33708a5cd3034bbee29bf00d to your computer and use it in GitHub Desktop.
Semaphores implemented using monitors and condition variables
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 | |
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