dtails
dtails

Reputation: 39

Swift run multiple block of codes asynchronously in background thread in order

Is this code below guaranteed to run in order if it's on the same thread? If not, is there way to make sure that the asynchronous background tasks are performed in order?

DispatchQueue.global().async {
  print("a")
}
DispatchQueue.global().async {
  print("b")
}

Upvotes: 0

Views: 4158

Answers (4)

leogdion
leogdion

Reputation: 2350

DispatchQueue are a level of abstraction above an actual Thread. The benefit of this is that Apple can essential decided whether an actual operating system Thread is necessary depending on a few factors:

  • The Operating System: watchOS, iOS, macOS, tvOS, etc...
  • The Hardware: Watch Series 1 vs Mac Pro vs iPhone SE, etc...
  • Power Constraints, CPU, etc...

Therefore, GCD basically gives the OS the ability to create a thread if it sees that as efficient for the user experience and the hardware the app is running on.

In the end, with the .async method each operation will start in order but each following operation will not wait for the previous to finish.

You can read more about how each API works in relation to asynchronous development here. There's specifically a section on GCD which focuses the various flags and types of queues.

Upvotes: 0

Ildar.Z
Ildar.Z

Reputation: 656

You can create your OperationQueue with 1 concurrent operation in the same time and any qos you need like this:

var operationQueue: OperationQueue = {

    let operation = OperationQueue()
    operation.qualityOfService = .userInitiated
    operation.maxConcurrentOperationCount = 1

    return operation
}()

operationQueue.addOperation {

}

So you can use any quality of service and it's guaranteed to run in order you pass it inside operation queue but not guaranteed finish in order.

Upvotes: 1

matt
matt

Reputation: 535616

Just do them in order in the same async code.

DispatchQueue.global().async {
  print("a")
  print("b")
}

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100533

DispatchQueue.global() is a concurrent queue which means any 2 tasks will run in parallel whatever 1 ends the first

if you need to run them serially then either chain them one after the other or create a custom serial queue and dispatch the tasks in it like

let serialQueue = DispatchQueue(label: "queuename")
serialQueue.sync { 
   // task 1
}

serialQueue.sync { 
  // task 2     
}

Upvotes: 2

Related Questions