基礎: 進程與線程
- 進程(process):操作系統(tǒng)資源分配的最小單元,資源管理角色:
- Memory: 代碼录语,數(shù)據(jù)
- Handles: files倍啥, devices, OS
- Threads: 主線程钦无,和其他線程逗栽,執(zhí)行代碼
- 線程(thread):是CPU執(zhí)行的最小單元
- OS scheduler:調度線程,決定哪些線程分配到CPU時間片
圖示:
image.png
go
- Go runtime scheduler: 創(chuàng)建和管理所有的goroutine失暂,綁定系統(tǒng)線程到logical processor彼宠,調度goroutine 到logical processor執(zhí)行,包含一個goroutine全局待調度隊列弟塞。
- logical processor: 每個logical processor 綁定到一個線程上凭峡,包含一個goroutine執(zhí)行隊列,調度執(zhí)行goroutine
- thread:一個thread用來執(zhí)行多個goroutine决记,在不同的時間
- goroutine:go里面的異步執(zhí)行函數(shù)摧冀, 比thread占用更少資源,更容易被調度執(zhí)行
- go弱化了thread概念系宫,讓logical processor來調度thread執(zhí)行索昂。
goroutine 調度過程
- goroutine 創(chuàng)建,放置在go runtime scheduler 的全局隊列扩借,等待被調度
- runtime scheduler 調度goroutine 到一個logical processor 椒惨,添加到logical processor 的執(zhí)行隊列,等待logical processor 調度
- 當正在執(zhí)行的goroutine 執(zhí)行一些阻塞調用潮罪,該thread與goroutine從logical processor解除關聯(lián)康谆,阻塞的goroutine等待阻塞調用返回
- 解除thread關聯(lián)時,logical processor 沒有一個可以調度的thread嫉到。所以logical processor重新創(chuàng)建一個線程關聯(lián)到logical processor沃暗,繼續(xù)調度自己的執(zhí)行隊列
- 當阻塞調用返回時,goroutine 返回到logical processor 的執(zhí)行隊列等待被調度何恶;空閑的thread資源保留孽锥,等待將來被使用。
圖示:
image.png
Concurrency vs parallelism
Parallelism(并行):
- Parallelism can only be achieved when multiple pieces of code are executing simultaneously against different physical processors. 并行執(zhí)行导而,利用多核處理器的物理資源忱叭,并行執(zhí)行代碼
- Parallelism is about doing a lot of things at once. 在現(xiàn)一時間同時做多個事情
Concurrency(并發(fā)):
- Concurrency is about managing a lot of things at once。在同樣的時間內管理執(zhí)行多個事情
- 在大多數(shù)情況下今艺,并發(fā)的性能大于并行韵丑,因為操作系統(tǒng)和物理硬件的壓力更小,允許系統(tǒng)做更多的事情
圖示:
image.png
疑問虚缎?
go弱化了thread概念撵彻,讓logical processor來調度thread執(zhí)行钓株。go runtime 是否在維護一個線程池,讓logical processor 調度使用陌僵?
- 目前go默認可以使用10000個線程轴合,可以通過SetMaxThreads設置
- 《go in action 》 第六章里有提到因為系統(tǒng)調用返回的goroutine,會放到logical processor的調度隊列里碗短;與之關聯(lián)的線程受葛,會放置到后續(xù)使用
基于以上兩點,猜測確實有維護一個線程池偎谁。目前還沒找到相關文檔总滩,關乎這方面底層的介紹