I have a thread-safe class which uses synchronization technique with async writes and synchronous reads. I see that swift Actors offer thread safety the same way, hence, I am thinking of migrating it to use Modern Concurrency techniques.
I want to migrate class A, which performs its reads synchronously and for the writes, it sends its synchronizationQueue to another class (a cache), to retrieve messages and then asynchronously perform writes. A code sample is below. While migrating to Actors/Modern concurrency, how can we perform this type of synchronization between classes as these are sharing a single queue to perform tasks?
class ThreadSafeClassA {
var messages = [String]()
let messageCache: ThreadSafeClassB
let synchronizationQueue = DispatchQueue("mySynchronizationQueue")
init() {
messageCache = ThreadSafeClassB(queue: synchronizationQueue)
}
func readFromMessages() -> [String] {
synchronizationQueue.sync {
messages
}
}
func writeToMessages() {
messageCache.retrieveMessages(on: synchronizationQueue) {
messages.append($0)
}
}
}
class ThreadSafeClassB {
init(synchronizationQueue: DispatchQueue) {
}
func retriveMessages(on: DispatchQueue, completionHandler: @escaping (([String]) -> Void)) {
synchronizationQueue.async {
// calls completion handler
}
}
}