3

I have a function readData reading data from HealthKit that takes a few seconds to execute. This function can be called from multiple threads/places, but I want each call to execute in a queue, one at a time, rather than in parallel.

Is there a simple way to use GCD or OperationQueues to achieve this in Swift for iOS?

Pratik Stephen
  • 2,175
  • 1
  • 11
  • 11

1 Answers1

5

Yes, a serial DispatchQueue should solve your problem. Make sure that you create it in a scope that each of your functions that need to can access it.

let serialQueue = DispatchQueue(label: "serialQueue")
serialQueue.async{  //call this whenever you need to add a new work item to your queue
    //call function here
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • I had a similar question and I thought about DispatchQueue however my concern is @pratik above is asking for sequential execution of the process submitted (not parallel). Dispatch Queues are serial in nature (FIFO) however the execution of those processes can be still in parallel in multi-core processor. – helloWorld Dec 04 '18 at 07:53