Created
October 24, 2018 18:38
-
-
Save mrnkr/e09e614d4d967418f270bae815730163 to your computer and use it in GitHub Desktop.
Readers and writers problem solved in swift using semaphores
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 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 | |
| } | |
| } | |
| func randomString(length: Int) -> String { | |
| let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" | |
| return String((0...length-1).map{ _ in letters.randomElement()! }) | |
| } | |
| var wrt: Semaphore = Semaphore(n: 1) | |
| var mutex: Semaphore = Semaphore(n: 1) | |
| var readers: Int = 0 | |
| var ran = 0 | |
| var book: String = "" | |
| func reader(read: (String) -> Void) { | |
| while ran < 100 { | |
| mutex.P() | |
| readers = readers + 1 | |
| if readers == 1 { | |
| wrt.P() | |
| } | |
| mutex.V() | |
| read(book) | |
| mutex.P() | |
| readers = readers - 1 | |
| if readers == 0 { | |
| wrt.V() | |
| } | |
| mutex.V() | |
| } | |
| } | |
| func writer() { | |
| while ran < 100 { | |
| wrt.P() | |
| book = book + randomString(length: 2) | |
| wrt.V() | |
| } | |
| } | |
| DispatchQueue.global(qos: .userInitiated).async { | |
| writer() | |
| } | |
| DispatchQueue.global(qos: .userInitiated).async { | |
| writer() | |
| } | |
| DispatchQueue.global(qos: .userInitiated).async { | |
| reader { (b: String) in | |
| print("Reader 1 just read \(b)") | |
| ran = ran + 1 | |
| } | |
| } | |
| DispatchQueue.global(qos: .userInitiated).async { | |
| reader { (b: String) in | |
| print("Reader 2 just read \(b)") | |
| ran = ran + 1 | |
| } | |
| } | |
| DispatchQueue.global(qos: .userInitiated).async { | |
| reader { (b: String) in | |
| print("Reader 3 just read \(b)") | |
| ran = ran + 1 | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment