Created
August 9, 2021 09:22
-
-
Save JarvisTheAvenger/2bb04e5ca2a0b848e9e7e6a636e6f049 to your computer and use it in GitHub Desktop.
This file contains 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 Foundation | |
// Concurrent queue | |
// When the order of execution of tasks doesn't matter, you can use concurrent queue. | |
// Concurrent queue are faster than serial queue. | |
// Concurrent queue can create race conditions in the code. | |
// NSLock - Used to avoid the race condition. | |
var balance = 5000 | |
let lock = NSLock() | |
struct Bank { | |
let withdrawType: String | |
func withdraw(amount: Int) { | |
lock.lock() | |
if balance > amount { | |
print("\(withdrawType) : - Sufficient balance proceed with transcation!!!") | |
Thread.sleep(forTimeInterval: Double.random(in: 0...4)) | |
balance = balance - amount | |
print("\(withdrawType): - \(amount) Rs withdrawn from your account") | |
print("\(withdrawType): - Current balance \(balance) Rs") | |
} else { | |
print("\(withdrawType): - You have insufficient balance in your account") | |
} | |
lock.unlock() | |
} | |
} | |
let queue = DispatchQueue(label: "concurrentQueue", attributes: .concurrent) | |
queue.async { | |
let bank = Bank(withdrawType: "ATM") | |
bank.withdraw(amount: 3000) | |
} | |
queue.async { | |
let bank = Bank(withdrawType: "UPI") | |
bank.withdraw(amount: 4000) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment