https://priteshrnandgaonkar.github.io/concurrency-with-swift-3/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
import UIKit class ViewController: UIViewController { var button : UIButton? = nil func action(selector:UIButton) { print("Button Clicked") } override func viewDidLoad() { print("--viewDidLoad--") super.viewDidLoad() self.button = UIButton(type: UIButtonType.roundedRect) as UIButton self.button?.backgroundColor = UIColor.orange self.button?.addTarget(self, action: #selector(action), for: UIControlEvents.touchUpInside) self.button?.frame = CGRect(x: 80, y: 60, width: 200, height: 80) self.button?.setTitle("Push Me", for: .normal) print("button created") self.view.addSubview(self.button!) print("view hieararchy added button") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let dispatchQueue = DispatchQueue(label: "com.prit.TestGCD.DispatchQueue", attributes: .concurrent) let semaphore = DispatchSemaphore(value: 2) dispatchQueue.async { //At this point the readers are not locking the resource. //They are only locking the entry section so no other reader can enter it while they are in it. if semaphore.wait(timeout: .distantFuture) == .success { print("success adding block 1") } else { print("timed out") } //Once the first reader is in the entry section, it will lock the resource. Doing this will prevent any writers from accessing it print("enter critical section") Thread.sleep(forTimeInterval: 5) print("exit critical section") //Once the reader is done executing the entry section, it will unlock it by signaling the mutex semaphore.signal() } dispatchQueue.async { if semaphore.wait(timeout: .distantFuture) == .success { print("success adding block 2") } else { print("timed out") } print("Sema block 2 sleep for 2 sec") Thread.sleep(forTimeInterval: 2) print("Sema block 2 signal") semaphore.signal() } dispatchQueue.async { if semaphore.wait(timeout: .distantFuture) == .success { print("success for adding block 3") } else { print("timed out") } print("Sema block 3 signal") semaphore.signal() } dispatchQueue.async { if semaphore.wait(timeout: .distantFuture) == .success { print("success for adding block 4") } else { print("timed out") } print("Sema block 4 signal") semaphore.signal() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } |