基础: 进程与线程
- 进程(process):操作系统资源分配的最小单元,资源管理角色:
- Memory: 代码,数据
- Handles: files, devices, OS
- Threads: 主线程,和其他线程,执行代码
- 线程(thread):是CPU执行的最小单元
- OS scheduler:调度线程,决定哪些线程分配到CPU时间片
图示:

image.png
go
- Go runtime scheduler: 创建和管理所有的goroutine,绑定系统线程到logical processor,调度goroutine 到logical processor执行,包含一个goroutine全局待调度队列。
- logical processor: 每个logical processor 绑定到一个线程上,包含一个goroutine执行队列,调度执行goroutine
- thread:一个thread用来执行多个goroutine,在不同的时间
- goroutine:go里面的异步执行函数, 比thread占用更少资源,更容易被调度执行
- go弱化了thread概念,让logical processor来调度thread执行。
goroutine 调度过程
- goroutine 创建,放置在go runtime scheduler 的全局队列,等待被调度
- runtime scheduler 调度goroutine 到一个logical processor ,添加到logical processor 的执行队列,等待logical processor 调度
- 当正在执行的goroutine 执行一些阻塞调用,该thread与goroutine从logical processor解除关联,阻塞的goroutine等待阻塞调用返回
- 解除thread关联时,logical processor 没有一个可以调度的thread。所以logical processor重新创建一个线程关联到logical processor,继续调度自己的执行队列
- 当阻塞调用返回时,goroutine 返回到logical processor 的执行队列等待被调度;空闲的thread资源保留,等待将来被使用。
图示:

image.png
Concurrency vs parallelism
Parallelism(并行):
- Parallelism can only be achieved when multiple pieces of code are executing simultaneously against different physical processors. 并行执行,利用多核处理器的物理资源,并行执行代码
- Parallelism is about doing a lot of things at once. 在现一时间同时做多个事情
Concurrency(并发):
- Concurrency is about managing a lot of things at once。在同样的时间内管理执行多个事情
- 在大多数情况下,并发的性能大于并行,因为操作系统和物理硬件的压力更小,允许系统做更多的事情
图示:

image.png
疑问?
go弱化了thread概念,让logical processor来调度thread执行。go runtime 是否在维护一个线程池,让logical processor 调度使用?
- 目前go默认可以使用10000个线程,可以通过SetMaxThreads设置
- 《go in action 》 第六章里有提到因为系统调用返回的goroutine,会放到logical processor的调度队列里;与之关联的线程,会放置到后续使用
基于以上两点,猜测确实有维护一个线程池。目前还没找到相关文档,关乎这方面底层的介绍