Concurrency

Rule of Thumb: Choose the highest level abstraction that gets the job done and keep your concurrency model very simple.

Basics

Process vs Thread

  • Processes are the abstraction of running programs
  • Threads are the unit of execution in a process
  • Threads are managed and scheduled by operating system scheduler
  • A process contains one or more threads.

Concurrency vs Parallelism

  • Concurrency is when two or more tasks can start, run, and complete in overlapping time periods.
  • Concurrency can be achieved by using time-slicing or parallelism.
  • Parallelism is when tasks literally run at the same time, e.g., on a multicore processor.

Single Core Single-core devices can achieve concurrency through time-slicing. They would run one thread, perform a context switch, then run another thread.

Multi-Core Multi-core devices on the other hand, execute multiple threads at the same time via parallelism.

Parallelism requires concurrency, but concurrency does not guarantee parallelism.

Deadlock

Two (or sometimes more) items — in most cases, threads — are said to be deadlocked if they all get stuck waiting for each other to complete or perform another action. The first can’t finish because it’s waiting for the second to finish. But the second can’t finish because it’s waiting for the first to finish.

If you call sync and target the current queue you’re already running on. This will result in a deadlock situation.

Thread Safe

  • A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads.
  • In particular, it must satisfy the need for multiple threads to access the same shared data
  • And the need for a shared piece of data to be accessed by only one thread at any given time
  • Don't have mutable state whenever possible. Copies, copies, copies.

Thread safe code can be safely called from multiple threads or concurrent tasks without causing any problems such as data corruption, or app crashes. Code that is not thread safe must only be run in one context at a time.

Why not using Thread ?

One problem that can arise from directly using threads is that the number of active threads increases exponentially if both your code and underlying framework code spawn their own threads.

results matching ""

    No results matching ""