|
| 1 | +import UIKit |
| 2 | +import PlaygroundSupport |
| 3 | + |
| 4 | +PlaygroundPage.current.needsIndefiniteExecution = true |
| 5 | + |
| 6 | +/* |
| 7 | + Thank you for watching the video, I hope it was helpful. If you have doubts then please feel free to reach out via comments or social media I will be happy to answer your question. |
| 8 | + |
| 9 | + If you have not subscribed to the channel then please do subscribe and don't forget to turn on the bell notification, and do share the channel with your friends. |
| 10 | + |
| 11 | + Regards, |
| 12 | + Ravi (CodeCat15) |
| 13 | + |
| 14 | + */ |
| 15 | + |
| 16 | + |
| 17 | +let highPriorityQueue = DispatchQueue.global(qos: .userInitiated) |
| 18 | +let lowPriorityQueue = DispatchQueue.global(qos: .utility) |
| 19 | + |
| 20 | +let codecat15Semaphore = DispatchSemaphore(value: 1) |
| 21 | +let codecat15BrotherSemaphore = DispatchSemaphore(value: 1) |
| 22 | + |
| 23 | + |
| 24 | +func requestForResource(resource: String, prioritySymbol: String, semaphore: DispatchSemaphore) |
| 25 | +{ |
| 26 | + debugPrint("\(prioritySymbol) is waiting for resource = \(resource)") |
| 27 | + semaphore.wait(timeout: DispatchTime.now() + 5) |
| 28 | +} |
| 29 | + |
| 30 | +func prepareBreakfast(queue: DispatchQueue, prioritySymbol: String, firstResource: String, firstSemaphore: DispatchSemaphore, secondResource: String, secondSemaphore: DispatchSemaphore) |
| 31 | +{ |
| 32 | + queue.async { |
| 33 | + |
| 34 | + requestForResource(resource: firstResource, prioritySymbol: prioritySymbol, semaphore: firstSemaphore) |
| 35 | + |
| 36 | + for i in 0...10 { |
| 37 | + if(i == 4) |
| 38 | + { |
| 39 | + requestForResource(resource: secondResource, prioritySymbol: prioritySymbol, semaphore: secondSemaphore) |
| 40 | + } |
| 41 | + debugPrint("\(prioritySymbol) \(i)") |
| 42 | + } |
| 43 | + |
| 44 | + debugPrint("signal called") |
| 45 | + firstSemaphore.signal() |
| 46 | + secondSemaphore.signal() |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +prepareBreakfast(queue: highPriorityQueue, prioritySymbol: "🐈", firstResource: "Pan", firstSemaphore: codecat15Semaphore, secondResource: "Oil", secondSemaphore: codecat15BrotherSemaphore) |
| 51 | + |
| 52 | +prepareBreakfast(queue: lowPriorityQueue, prioritySymbol: "🦖", firstResource: "Oil", firstSemaphore: codecat15BrotherSemaphore, secondResource: "Pan", secondSemaphore: codecat15Semaphore) |
| 53 | + |
0 commit comments