I was asked to implement a thread safe dictionary in swift, I used the common approach:
class MutableDictionary {
var dictionary: [String : Any] = [:]
var queue = DispatchQueue(label: "queue", attributes: .concurrent)
func object(for key: String) -> Any? {
queue.sync {
return dictionary[key]
}
}
func set(_ object: Any?, for key: String) {
queue.async(flags: .barrier) {
self.dictionary[key] = object
}
}
}
However, the following up question is:
- What's the difference with using
concurrent+barriervs just using aserialQueuefor setting in this case? - I did a testing on playground, I wrapped the get and set with 1000 time for loop, it turns out that the behavior for both serial and concurrent queue is almost the same.
- Why the setting always raise an error?

- What does concurrent queue do better in this case (for both get and set) compared to a serial queue?
- In iOS, when should I choose serial queue over concurrent queue? And vice-versa?
1、with
barrier, the concurrent queue is temporary able to execute one task at a time.However, the serialQueue can only perform one task at a time.
2、Given you only use the queue to read/write, they obviously have the same effect. if you put another kind task to it, apparently the concurrent queue cost less and that is the real difference.
3、Submitted to async object address will be defined when your object is a class. You will have a bad address when you give the class member a new value, So you cannot access it and the error comes. You can have a try by struct .
4、refer to
answer 1.5、Sometimes when you want the task to be performed faster, concurrentQueue first. If you want to execute tasks orderly, serialQueue do the better.