Member-only story

Concurrency and Parallelism

--

Concurrency = Multiple tasks appear to run at once (interleaved execution). It allows an app to make progress on multiple tasks by switching between them, even if only one task is being executed at a given moment.

How?

By using Context switching and time slicing.

Parallelism = Multiple tasks actually run at the same time on multiple cores.

How to achieve multithreading in swift

  1. GCD
  2. OperationQueue

Modern Approach

  1. Dispatch Group
  2. Dispatch Work Item
  3. Dispatch Barrier
  4. Semaphore
  5. Actor
  6. Async await

What is GCD?

GCD is a queue based API that allows to execute work in thread pool in FIFI order. GCD manages the collections of dispatch queue.

and dispatch queue we have two types: main queue and global queue

A dispatch queue executed tasks either serially or concurrently but always in FIFO.

Example:


// ****************** Serial Queue (FIFO Order)**********************
let serialQueue = DispatchQueue(label: "com.example.serialQueue")

serialQueue.async {
print("🔹 Task 1")
}
serialQueue.async {
print("🔹 Task 2")
}
serialQueue.async {
print("🔹 Task 3")
}

//**** Output
📌 Output (FIFO Order)…

--

--

No responses yet