How do we migrate two classes to Modern Concurrency, which share a single DispatchQueue(synchronization) to perform tasks?

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 ClassA { 
   var messages = [String]()
   let messageCache: ClassB
   let synchronizationQueue = DispatchQueue("mySynchronizationQueue")

   init() {
      messageCache = ClassB(queue: synchronizationQueue)
   }

   func readFromMessages()  -> [String] {
      synchronizationQueue.sync {
       messages
     }
  }

 func writeToMessages() {
   messageCache.retrieveMessages(on: synchronizationQueue) {
      messages.append($0)
   }
 }
 }
class ClassB { 
   init(synchronizationQueue: DispatchQueue) {
   }

  func retriveMessages(on: DispatchQueue, completionHandler: @escaping (([String]) -> Void)) {
    synchronizationQueue.async {
      // calls completion handler
   }
  }
}

You can replace DispatchQueue with actor-specific methods for synchronization and use shared actor executors if multiple actors need to coordinate on the same queue. Also test performance with SerialExecutors if used for logging to avoid overhead.

This topic was automatically closed after 166 days. New replies are no longer allowed.