进程与线程

Posted on Apr 13, 2023

进程是资源分配的最小单位,线程是cpu调度的最小单位。这句话好像说了什么,让你感觉好像理解了进程与线程的关系,但是好像理解只停留在概念上。 Linux2.x版本才支持线程,那在这之前线程就不是cpu调度的最小单位了?

Both threads and processes are really just one thing: a “context of execution”.

A “context of execution”, hereby called COE, is just the conglomerate of all the state of that COE. That state includes things like CPU state (registers etc), MMU state (page mappings), permission state (uid, gid) and various “communication states” (open files, signal handlers etc).

Traditionally, the difference between a “thread” and a “process” has been mainly that a threads has CPU state (+ possibly some other minimal state), while all the other context comes from the process.

这是Linus Torvalds在mail list里关于进程 线程区别的描述,从内核的角度来说,它们本质都是COE,对应task_struct

pthreads library can export the limited pthreads interface to users who want to use that way of looking at COE’s. 而pthread使用forkclone之类的syscall控制一些状态的共享,来实现进程和线程的抽象,比如pthread使用clone来控制线程共享进程的堆内存

理解了COE再去理解协程就变得顺理成章了。协程作为用户态的一个COE,我们就要自己保存状态。这个状态无非就是上下文切换时CPU当前的状态

1
2
3
4
5
TEXT runtime·saveContext(SB),NOSPLIT,$0-8
    MOVQ    BX, bx-8(SP)    
    LEAQ    bx-8(SP), BP  
    MOVQ    BP, 0(SP)
    RET

然后再把我们准备调度的协程恢复

1
2
3
4
TEXT runtime·restoreContext(SB),NOSPLIT,$8-0
    MOVQ    0(SP), BP
    MOVQ    bx-8(SP), BX
    RET