How can we implement concurrency thread using protocol in swift?

SKumar

I was asked this question in interview for iOS developer role.

// Please design a read-write task queue where you can tag the reader task with label,
// where the the task with the same label should be executed sequentially, and the 
// tasks with different labels could be executed concurrently. However, the writer 
// would get the exclusive access where no concurrent task would happen at the 
// same time with the writer task

// For example:
protocol ConcurrentQueueWithSerialization {
  // Submits a labeled task.
  // All tasks with the same label will be serialized.
  // Tasks with different labels will run concurrently.
  // Use this method to submit a "read" operation from a particular reader.
  func async(with label: String, task: @escaping () -> Void)

  // Submits a task that will run concurrently with all other tasks regardless of their labels.
  func async(task: @escaping () -> Void)

  // Submits a labeled and delayed task.
  func asyncAfter(deadline: DispatchTime, with label: String, task: @escaping () -> Void)

  // Submits an unlabeled and delayed task.
  func asyncAfter(deadline: DispatchTime, task: @escaping () -> Void)

  // Submits a barrier task. Only one barrier task is allowed to run at a time.
  // Works as a critical section for the queue.
  // Use this method to submit a writer task.
  func asyncBarrier(task: @escaping () -> Void)
}

class MyDispatchQueue: ConcurrentQueueWithSerialization {
  //TODO: write your implementation

} 

Interviewer asked me to implement above protocol in MyDispatchQueue class. I tried but could not find solution. Please help me. Thanks in advance.

Rob

Previously I suggested using target queues, but even better, create a primary concurrent queue, and then create serial queues for the named queues, and then dispatch everything through that primary concurrent queue. Unlike the target queue approach, this will honor the scheduling of tasks dispatched to the named queues with those dispatched to the unnamed queue.

With that implementation, here's an example (an Instruments "Points of Interest" profile) of this where I added tasks for queues named "fred" and "ginger" and also one which was added to an unnamed queue, I then added a barrier task, and then added two more tasks to each of the aforementioned queues.

enter image description here

As you can see, it respects the serial nature of the named queues, the unnamed queue is concurrent, and all these queues are concurrent with respect to each other, but the barrier is a barrier across all the queues.

class MyDispatchQueue: ConcurrentQueueWithSerialization {
    private var namedQueues = [String: DispatchQueue]()
    private var queue = DispatchQueue(label: Bundle.main.bundleIdentifier! + ".target", attributes: .concurrent)
    private let lock = NSLock()

    private func queue(with label: String) -> DispatchQueue {
        lock.lock()
        defer { lock.unlock() }

        if let queue = namedQueues[label] { return queue }

        let queue = DispatchQueue(label: Bundle.main.bundleIdentifier! + "." + label)
        namedQueues[label] = queue
        return queue
    }

    func async(with label: String, task: @escaping () -> Void) {
        queue.async {
            self.queue(with: label).sync(execute: task)
        }
    }

    func async(task: @escaping () -> Void) {
        queue.async(execute: task)
    }

    func asyncAfter(deadline: DispatchTime, with label: String, task: @escaping () -> Void) {
        queue.asyncAfter(deadline: deadline) {
            self.queue(with: label).sync(execute: task)
        }
    }

    func asyncAfter(deadline: DispatchTime, task: @escaping () -> Void) {
        queue.asyncAfter(deadline: deadline, execute: task)
    }

    func asyncBarrier(task: @escaping () -> Void) {
        queue.async(flags: .barrier, execute: task)
    }
}

Note, I also synchronize access to the namedQueues array, to ensure the thread-safety of this class.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can i implement concurrency in C like we do in go?

How can I "explicitly" implement a protocol in swift? If it is impossible, why?

How can we make 'static' variables Thread-Safe in swift?

How can we implement componentWillUnmount using react hooks?

How can we implement the exclusion function with using API

Implement delegate using generic protocol in Swift

Can we implement Web session management relying on HTTPS protocol

Spring Boot:How can we implement multiple @Scheduled tasks with each having its own thread pool?

How to implement objective C protocol in swift class?

Swift question: how can we init an non-optional variable in a if else block if it's of protocol type?

How can we send dot in smtp protocol

Can we implement linked lists using inheritance?

How can I use Swift protocol function like as Android interface listener implement?

How can we add image in UITableView section header using swift?

How do we increase or decrease brightness of a tvOS app using Swift 3? Also, how do we implement a customized sleep timer here?

Can we edit properties of "let" protocol properties in Swift?

How to implement HTTP protocol using WebRTC?

How to implement an IPC protocol using Boost ASIO?

How can we implement modularity in Haskell

How I can implement Login / Logout Navigation using UserDefaults in swift?

How can i implement multiselect with DropDown using swift 5?

How to implement concurrency in hibernate

Can't use concrete subclass to implement a property in protocol in Swift

How can we create a 'skeleton type' of an object that we should implement?

How can we "disable" thread pooling in Jetty

What do we mean by Tracking In styling ? How we can implement Tracking w.r.t styling using xsl?

How can we implement app engine service to service communication using internal communication, isolated from public internet?

Python - How can I implement a 'stoppable' thread?

How can we Send Different messages to rabbitmq per thread using jmeter AMQP publisher plugin?