I'm debugging a swift class that I have inherited in a project. There was an attempt to create a thread safe dictionary using a swift dictionary with a semaphore. The code fails in multi threaded environment - the swift dictionary is treated as a struct and is copied on mutation, regardless of the semaphore.
I'm trying to understand: Will replacing a swift struct based dictionary with a core foundation NSMutableDictionary (with a semaphore) ensure thread safety of the code?
I see this answer for Objective-C, but my question is about modifying the swift code.
public class ThreadSafeDictionary<KeyType: Hashable, ValueType> {
private var dictionary: [KeyType: ValueType] = [:]
//change to:
private let dictionary = NSMutableDictionary() //will this make the mutating code thread safe?
public func add(key: KeyType, value: ValueType) {
// semaphore wait
// set value in dictionary
// semaphore signal
}
}
Or - is there a way to use swift keywords like mutating or inout to make sure that the semaphores would prevent multiple threads from each working with a copy of a swift dictionary?
Updated: there was a bug in a higher level code, creating 2 independent instances of ThreadSafeDictionary. Fixing that resolved the concurrency issue.