I attempting to grasp how precisely Job works with loop.
I used to be experimenting with outputting numbers to the console and seen that I used to be getting a consequence that was not what I anticipated.
actor ThreadSafeCollection {
personal var assortment: [T] = []
func add(_ aspect: T) {
assortment.append(aspect)
}
func getAll() -> [T] {
return assortment
}
func take away(at index: Int) {
guard assortment.indices.incorporates(index) else { return }
assortment.take away(at: index)
}
}
var safeCollection: ThreadSafeCollection = ThreadSafeCollection()
@Sendable func firstIterate() async -> Job<[Int], By no means> {
Job {
for i in 0..<500 {
await safeCollection.add(i)
}
return await safeCollection.getAll()
}
}
@Sendable func secondIterate() async -> Job<[Int], By no means> {
Job {
for i in 0..<500 {
await safeCollection.add(i)
}
return await safeCollection.getAll()
}
}
Job {
let consequence = await withTaskGroup(of: [Int].self, returning: [Int].self) { taskGroup in
taskGroup.addTask { await firstIterate().worth }
taskGroup.addTask { await secondIterate().worth }
var collected = [Int]()
for await worth in taskGroup {
collected.append(contentsOf: worth)
}
return collected
}
print(consequence.sorted(by: <))
}
On this instance, I iterate 2 instances to 500 by calling the primary Iterate() and secondIterate() strategies, because of which I anticipate to get an array with numbers during which every quantity shall be repeated 2 instances. However as an alternative, I see every quantity 4 instances within the console.
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4...
And besides, I noticed that at the end of the array, the numbers are repeated not 4 times as at the beginning, but 3.
...494, 494, 494, 495, 495, 495, 496, 496, 496, 497, 497, 497, 498, 498, 498, 499, 499, 499]
Can anybody clarify why that is occurring?