Created
August 31, 2018 07:49
-
-
Save seivan/a50aa101df1db3320a57ce920076d994 to your computer and use it in GitHub Desktop.
This shouldn't work, but it works. Thus undefined behaviour.
This file contains hidden or 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
| 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