# 行程 Process & 執行緒 Thread & 微執行緒 Coroutine

## 行程 Process & 執行緒 Thread & 微執行緒 Coroutine 的關係

我個人是覺得可以想像成 Process 是公司，不同公司是各自獨立的，有各自的資源，例如營業額、土地、廠房。但是彼此也可以相互的合作。可以轉職跳換不同的公司，但是其耗費的成本就比較高。Thread 就是公司間的各部門，一間公司由一個或多個部門所組成。部門間的轉換相對容易，且共享這一間公司的所有資源。Coroutine 則可以視為部門中的成員，可以視為已經是最小的執行單位。

## 什麼是行程 Process

In computing, a **process** is the instance of a computer program that is being executed by one or many threads. -- Wikipedia

可以把 Process 看作是一個包含一個或多個 Thread 的容器，執行程式的 Instance。Process 之間彼此獨立有各自的地址空間，會有各自的 CPU Time、Memory、Disk 等。再細分的話又可以分為 Kernel Process & User Process。

因為 Process 是各自獨立的，所以可以達到 Parallel。

Process 會用不同的 state 來記錄其狀態。
- new (新產生)：該進程正在產生中
- ready (就緒)：該進程正在等待 CPU 分配資源，只要一拿到資源就可以馬上執行
- running (執行)：該進程取得 CPU 資源並且執行中
- waiting (等待)：該進程在等待某個事件的發生，可能是等待 I/O 設備輸入輸出完成或者是接收到一個信號，也可以想成是被 block (阻塞) 住
- exit (結束)：該進程完成工作，將資源釋放掉

### Pros and Cons

#### Pros

彼此獨立可以忽略 Race condition 的問題。

#### Cons

進程的建立及切換（context switch）的性能開銷比較大，因為涉及到 OS 資源的切換，彼此間要通信也比較複雜及耗時。

## 什麼是執行緒 Thread

In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system. The implementation of threads and processes differs between operating systems, but in most cases a thread is a component of a process.  -- Wikipedia

每一個 Thread 負責某一項功能，同一個 Process 底下的 Thread 共享資源，如記憶體、變數等。

### Multithread

在多執行緒中，執行緒屬於同步機制，在同時間運行的執行緒，若執行緒間同時存取或修改全域變數，則容易發生同步問題（Race condition）。若執行緒之間互搶資源，則可能產生死結（Deadlock）。因為是共享資源的方式，所以需要記住 Multithread 是 Concurrent 而不是 Parallel。


### Thread Pool


## 什麼是微執行緒 Coroutine

Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed. -- Wikipedia

Coroutine 的概念，在 1958 年由 Melvin Edward Conway 提出。一種類似多執行緒的單執行緒程式概念，且可以避開多執行緒的 Race condition 問題，因為他是單執行緒不會有第二個執行緒來搶著操作。

Coroutine 屬於非同步機制，在執行過程擁有自己的上下文，同時具有可暫時儲存上下文的機制，當一個 Coroutine 儲存後，執行完其他任務可在重新進入，並且從上一次執行的狀態繼續進行。這樣的功能讓程式可以達到分段執行。

Coroutine 的調度完全由使用者控制，Process 和 Thread 的調用都是依照了 CPU 內的演算法去操作，屬於搶占式調度，可以主動搶奪執行的控制權。Coroutine 是不行的，只能進行非搶佔式的調度。

## 結語

Process & Thread 的執行會牽扯到 Concurrent & Parallel 的概念。然後 Thread 和 Coroutine 的執行概念可以延伸到同步與非同步的概念，可以參考 JavaScript 中的 Event Loop 或是 JavaScript 和 Python 中的 `async/await`。

## 延伸閱讀

- [並行 Concurrent & 平行 Parallel]()
- [Process](https://www.wikiwand.com/en/Process_(computing))
- [Thread](https://www.wikiwand.com/en/Thread_(computing))
- [Coroutine](https://www.wikiwand.com/en/Coroutine)
- [進程 (Process)、線程 (Thread)、協程 (Coroutine) 的概念講解](https://blog.kennycoder.io/2020/05/16/進程-Process-、線程-Thread-、協程-Coroutine-的概念講解)
