Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This shouldn't work, but it works. Thus undefined behaviour.
func update(_ arg: inout String) {
arg = "UPDATED \(arg)"
}
public class SystemWork {
let mainQueue = DispatchQueue.init(label: "mainQueue", qos: .userInitiated, attributes: [], autoreleaseFrequency: .inherit, target: nil)
let workerQueue = DispatchQueue.init(label: "workerQueue", qos: .userInitiated, attributes: [.concurrent], autoreleaseFrequency: .inherit, target: nil)
let systemQueue = DispatchQueue.init(label: "systemQueue", qos: .userInitiated, attributes: [.concurrent], autoreleaseFrequency: .inherit, target: nil)
var results: Array<Int> = []
let waiter = DispatchGroup()
var dict = Dictionary<Int, String>()
let range = (0..<100)
public init() {
self.range.forEach { self.dict[$0] = "HI \($0)" }
}
public func work() {
print("WORK START")
// range.forEach { id in
// withUnsafeMutablePointer(to: &self.dict[id, default: ""]) { data in
// self.workerQueue.async(group: self.waiter) {
// update(&data.pointee)
// }
// }
// }
self.mainQueue.async(group: self.waiter) {
self.systemQueue.async(group: self.waiter) {
self.range.reduce(into: Array<Array<Int>>()) { result, int in
if (result.last?.count ?? 0) <= 64 {
var x = result.popLast() ?? Array<Int>()
x.append(int)
result.append(x)
}
else { result.append([int]) }
}
.forEach { ids in
ids.forEach { id in
withUnsafeMutablePointer(to: &self.dict[id, default: ""]) { data in
self.workerQueue.async(group: self.waiter) {
update(&data.pointee)
}
}
}
}
}
}
self.waiter.wait()
print("FINSIHED")
let finished = self.dict.values.filter { $0.hasPrefix("UPDATED ") }
print(finished.count)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.