Go Runtime

Go 运行时 Part 1 Runtime基础 01 Runtime是什么 Go runtime 是 Go 程序运行时依赖的一组基础设施。它不是 JVM 那种执行字节码的虚拟机,也不是一个需要单独安装和启动的外部进程。普通 Go 程序在编译链接之后,最终生成的是机器码可执行文件;runtime 会作为程序的一部分被链接进去,在程序启动、并发调度、内存分配、垃圾回收、栈管理、阻塞唤醒、网络轮询、定时器、panic/recover 等方面提供支持。 可以先把 Go 程序理解成两部分: TEXT用户代码 main.main 业务函数 package init 普通 goroutine 运行时 程序启动 goroutine 调度 栈增长 内存分配 GC channel/select timer netpoll syscall/signal panic/recover 这两部分最终在同一个进程里执行。用户代码看起来像是在直接调用函数、创建 goroutine、分配对象、读写 channel,但很多操作背后都会落到 runtime 的实现上。 例如下面这段代码: GOpackage main func main() { ch := make(chan int) go func() { ch <- 1 }() println(<-ch) } 表面上只有 make(chan int)、go func()、发送、接收几个语法动作;底层则至少涉及: ...

July 4, 2026

编译原理

编译原理:从源代码到可执行程序 高级语言中的变量、函数、结构体、接口、模块等概念更接近抽象语义;机器实际执行的是指令、寄存器操作、内存访问和跳转。编译器的核心任务是将高级语言程序转换为机器可执行的目标形式,并在这个过程中完成语法约束、类型约束、控制流约束、内存布局和目标平台约束的处理。 典型编译流程可以抽象为: TEXT源代码 -> 词法分析:字符流 -> Token 流 -> 语法分析:Token 流 -> AST -> 语义分析:AST -> 带类型、作用域、绑定关系的 AST -> 中间代码生成:AST -> IR -> 代码优化:IR -> 优化后的 IR -> 目标代码生成:IR -> 汇编 / 机器指令 -> 汇编与链接:目标文件 -> 可执行文件 这条流水线的关键不是“把文本翻译成另一段文本”,而是不断把程序转换为更适合下一阶段处理的结构化表示。Token 适合语法分析,AST 适合表达源代码结构,IR 适合数据流和控制流优化,机器指令适合在具体硬件上执行。 编译过程概览 以一段简单的 Go 代码为例: GOpackage main func add(a, b int) int { return a + b } 在编译器内部,它会经历类似下面的结构转换: ...

June 20, 2026

Go

draft need to be improved Slice GOtype slice struct { array unsafe.Pointer len int cap int } // 扩容 func nextslicecap(newLen, oldCap int) int { newcap := oldCap doublecap := newcap + newcap if newLen > doublecap { return newLen } const threshold = 256 if oldCap < threshold { return doublecap } for { // 1.25x newcap += (newcap + 3*threshold) >> 2 if uint(newcap) >= uint(newLen) { break } } // overflowed if newcap <= 0 { return newLen } return newcap } Map GOtype Map struct { used uint64 // The number of filled slots seed uintptr // the hash seed, computed as a unique random number per map. // The directory of tables. // Normally dirPtr points to an array of table pointers // dirPtr *[dirLen]*table dirPtr unsafe.Pointer dirLen int // 1 << globalDepth globalDepth uint8 // The number of bits to use in table directory lookups. globalShift uint8 // The number of bits to shift out, 64 - globalDepth writing uint8 // detect the race. tombstonePossible bool // whether a table in this map contains a tombstone. clearSeq uint64 // version number, used to detect map clears during iteration. } Swiss Table refer: Faster Go maps with Swiss Tables ...

March 2, 2026