Process vs. Threads
Process
- An instance of a running program is called a process.
- Process provides environment for program to execute.
- OS allocates memory.
- Code - machine instructions
- Data - Global data
- Heap - Dynamic memory allocation
- Stack - Local variables of function

Threads
- Threads are smallest unit of execution that CPU accepts
- Process has at least one thread(main thread)
- Process can have multiple threads.
- Threads share same address space.
- Threads run independent of each other.
- OS scheduler makes scheduling decisions at thread level, not process level.
- Threads can run concurrently or in parallel
- Threads are allocated fixed stack size
- 每個os 執行緒都有固定大小stack memory(2 mb),
- Thread 轉移到另一個 thread需要 context switch

Limitations of thread
- Fixed stack size
- C10K problem( Scheduler allocates a process a time slice for execution on CPU core), as we scale up number of threads, scheduler cycle increase and application can become less responsive!

Thread States

Context Switches are expensive
Process Context
- Process state
- CPU scheduling information
- Memory management information
- Accounting information
- I/O Status information
Thread Context
- Program counter
- CPU registers
- Stack (一般默認可能是 2 MB)
Goroutine
- stack 的大小限制可以1GB
- 協程更加輕量,一個程序可以隨意啟動成千上萬個goroutine
- goroutine 被Go runtime 所調度,這一點和線程不一樣。也就是說,Go 語言的並發是由Go 自己所調度的,自己決定同時執行多少個goroutine,什麼時候執行哪幾個。這些對於我們開發者來說完全透明,只需要在編碼的時候告訴Go 語言要啟動幾個goroutine,至於如何調度執行,我們不用關心。
- 不需要context switch, 成本較低
| 特徵 | 進程(Process) | 線程(Thread) | Goroutine |
|---|---|---|---|
| 執行方式 | 獨立執行 | 依賴進程 | 依賴進程 |
| 拥有资源 | 擁有獨立的內存、I/O資源、CPU時間等 | 共享進程內存、I/O資源、CPU時間等 | 共享進程內存、I/O資源、CPU時間等 |
| 切換成本(context switching) | 高,進程切換需要保存和恢復整個上下文 | 低,線程切換只需保存和恢復線程的上下文 | 非常低,Goroutine切換只需保存和恢復少量的上下文 |
| 并行處理 | 可以并行處理多個任務,但需要額外的同步機制 | 可以并行處理多個任務,但需要額外的同步機制 | 可以并行處理多個任務,並且使用通道(Channel)等內置機制進行同步 |
| 效率 | 效率較低 | 效率較高 | 效率更高 |
| 適用範圍 | 適用於需要隔離的任務,如獨立的應用程序、服務器進程等 | 適用於需要高效且低延遲的任務,如Web服務器、數據庫服務器等 | 適用於需要高效且低延遲的任務,如Web服務器、數據庫服務器等 |
進程是一個獨立的運行實例,它具有自己的地址空間和資源,可以獨立執行,但切換成本較高。 線程是在進程中運行的輕量級任務,它共享進程的資源,可以高效地進行任務切換,但需要額外的同步機制。 Goroutine是一個由Go語言提供的輕量級線程,它與線程類似,但使用了更高效的調度算
parallelism 並行
- 同時做很多事情
- 讓不同的代碼片段同時在不同的物理處理器上執行
concurrency 併發
- 同時管理很多事情, 這些事情可能只做一半就被暫停去做別的事情
- 併發效果比並行好