> For the complete documentation index, see [llms.txt](https://kdongs.gitbook.io/kdocs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kdongs.gitbook.io/kdocs/concurrency-and-parallelism/concurrency.md).

# Concurrency

## About

Concurrency is a simulation of running tasks at the "same time".

It happens when tasks run on the same core, or different virtual/logical cores.

{% hint style="info" %}
Each CPU physical core has a control unit, that switches between the logical cores when needed. *(Enabled by Hyper-Threading (HT) / Simultaneous Multi-Threading (SMT))*

This way the CPU can utilize idle execution units more efficiently. *(e.g, thread stalled when waiting for memory)*
{% endhint %}

{% hint style="info" %}
Also, the O.S scheduler doesn't distinguishes between physical or logical cores. It sees them all as physical independant cores, when it is assigning o.s threads to them.
{% endhint %}

## Thread

A thread is like the smallest execution unit.

Each thread executes a **sequence of intructions** and have a **context**, that stays in the CPU registers while the thread is executing in the CPU.

{% hint style="info" %}
The more threads try to concurrently execute, the slower it will be, because of all this context switching.
{% endhint %}

## Time Sharing

#### Context Switch

Context switching is the switch of contexts, in such a speed, that it looks like they are running on the same time.

{% hint style="info" %}
**Context**

A context is what defines the work environment of a process. (meaning its memory allocation basically)
{% endhint %}

The machine offers a pre-defined amount of time (`time-slice`) to each context to run.

## Scheduler (O.S)

The o.s scheduler is the task that will manage the context switch, to remove, contexts that do not cooperate and hang on the CPU.
