I get many warnings like this when I build an old project.
I asked AI chatbot which gave me several solutions, the recommended one is:
var hashBag = [String: Int]() func updateHashBag() async { var tempHashBag = hashBag // make copy await withTaskGroup(of: Void.self) { group in group.addTask { tempHashBag["key1"] = 1 } group.addTask { tempHashBag["key2"] = 2 } } hashBag = tempHashBag // copy back? }
My understanding is that in the task group, the concurrency engine ensures synchronized modifications on the temp copy in multiple tasks. I should not worry about this.
My question is about performance.
What if I want to put a lot of data into the bag? Does the compiler do some kind of magics to optimize low level memory allocations? For example, the temp copy actually is not a real copy, it is a special reference to the original hash bag; it is only grammar glue that I am modifying the copy.
Using a task group to protect a hash table is unlikely to yield sensible results. As to what would be better, it’s hard to say without knowing more about the context. You could, for example:
-
Confine access to this hash table to the main actor.
-
Or embed it with a custom actor.
-
Or protect it with
Mutex
.
If you explain more about the big picture, we should be able to suggest a more concrete path forward.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"