Last active
May 12, 2022 14:18
-
-
Save glennposadas/32004a3b8c6f0c269b077e34f6d6b78b to your computer and use it in GitHub Desktop.
semaphore+dispatchGroup+swift
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
// | |
// ViewController.swift | |
// semap | |
// | |
// Created by Glenn Posadas on 5/10/22. | |
// | |
import UIKit | |
class ViewController: UIViewController { | |
@IBOutlet var imgs: [UIImageView]! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
print("Batch one") | |
// BATCH ONE - first two imageviews | |
queue1.async(group: g) { | |
for index in 0...100 { | |
semaphore.wait() | |
let t = "https://dummyimage.com/500x600/000000/fff&text=" + "\(index)" | |
let url = URL(string: t)! | |
URLSession.shared.dataTask(with: url) { [weak self] data, resp, err in | |
guard let self = self else { return } | |
if let data = data, | |
let image = UIImage(data: data) { | |
DispatchQueue.main.async { | |
semaphore.signal() | |
let i = self.imgs[Int.random(in: 0...1)] | |
i.image = image | |
} | |
} | |
}.resume() | |
} | |
} | |
/// ---- | |
g.notify(queue: .main) { | |
print("GROUP 1 is done ----- ✅") | |
self.startSecondBatch() | |
} | |
} | |
func startSecondBatch() { | |
queue2.async(group: g2) { | |
print("START BATCH 222222") | |
for index in 0...50 { | |
semaphore.wait() | |
let t = "https://dummyimage.com/500x600/232ca6/fff&text=" + "\(index)" | |
let url = URL(string: t)! | |
URLSession.shared.dataTask(with: url) { [weak self] data, resp, err in | |
guard let self = self else { return } | |
if let data = data, | |
let image = UIImage(data: data) { | |
DispatchQueue.main.async { | |
semaphore.signal() | |
let i = self.imgs[Int.random(in: 2...3)] | |
i.image = image | |
} | |
} | |
}.resume() | |
} | |
} | |
/// ---- | |
g2.notify(queue: .main) { | |
print("GROUP 222222 is done ----- ✅") | |
self.startSecondBatch() | |
} | |
} | |
} | |
let url = URL(string: "https://source.unsplash.com/random/5120x1000")! | |
let queue1 = DispatchQueue.global(qos: .background) | |
let queue2 = DispatchQueue.global(qos: .background) | |
let semaphore = DispatchSemaphore(value: 4) | |
let g = DispatchGroup() | |
let g2 = DispatchGroup() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment