Home avatar

主题的晦涩 人生的短暂

[Paper Note] the Slab Allocator an Object-Caching Kernel Memory Allocator

原理

许多情况下,对象的构造和析构成本原大于内存的分配和回收。因此,既要优化内存分配,也要降低对象的构造/析构成本。

通过缓存对象维持对象的基本结构,在多次“使用”间复用此基本结构。对象在第一次分配时构造(初始化基本结构),回收时不析构(不毁坏此基本结构),下次分配直接返回缓存的对象。slab allocator 缓存的对象生命周期从“构造-使用-析构-构造-使用-析构……”变为“构造-使用-使用-使用-析构”。

致敬经典:K&R Allocator 内存分配器

k&R allocator 是Brain KernighanDennis Ritchie 的名著 The C Programming Language 第 8.7 节中介绍的一个简单 malloc 实现。因为该书被称为 K&R C,这个 malloc 实现也被称为 K&C allocator。

K&R allocator 的实现非常简洁,Linux 内核基于 K&R allocator 实现了用于嵌入式系统 slob allocator。见 slob: introduce the SLOB allocator,邮件摘要如下:

SLOB is a traditional K&R/UNIX allocator with a SLAB emulation layer,
similar to the original Linux kmalloc allocator that SLAB replaced.
It's signicantly smaller code and is more memory efficient. But like
all similar allocators, it scales poorly and suffers from
fragmentation more than SLAB, so it's only appropriate for small
systems.

本文的代码摘抄自 The C Programming Language 并修改了 C99 语法错误,你可以在这里获取完整代码 malloc.c

深入剖析 Go 语言运行时:IO 轮询器

netpoller 概述

考虑一个基于 goroutine-per-connection 模型的 TCP echo server:

import (
    "fmt"
    "io"
    "log"
    "net"
)

func worker(conn net.Conn) {
    defer conn.Close()
    b := make([]byte, 512)
    for {
        size, err := conn.Read(b)
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatal(err)
        }
        size, err = conn.Write(b[0:size])
        if err != nil {
            log.Fatal(err)
        }
    }
}

func main() {
    listner, err := net.Listen("tcp", "127.0.0.1:8080")
    if err != nil {
        log.Fatal(err)
    }
    for {
        conn, err := listner.Accept()
        if err != nil {
            log.Fatal(err)
        }
        go worker(conn)
    }
}

从用户侧看,系统该调用阻塞 goroutine,Go scheduler 调度其他 goroutine。问题在于,goroutine 复用在线程上,如果 IO 系统调用(如read(2)/write(2))阻塞,直接阻塞 goroutine 所在线程,Go scheduler 将没有机会调度 goroutine!

【译】内存屏障:软件黑客的硬件视角

译者序

Memory Barriers: a Hardware View for Software Hackers 是并发编程专家 Paul E. McKenney 的经典论文,该论文同时收录在他的著作 Is Parallel Programming Hard, And, If So, What Can You Do About It? 附录 C Why Memory Barriers? 中。

本文全文翻译该论文。



为什么中了邪的 CPU 设计者要让可怜的一无所知的软件设计者受内存屏障(memory barrier)的伤害?

【译】Go 语言内存模型:2022-06-06 版

译者序

原文 The Go Memory Model 描述 Go 语言内存模型,这里的内存模型实际上是“内存一致性模型”(memory consistency model)。笔者修改了格式错误并翻译全文。

The Go Memory Model 在内存一致性模型层面,描述 Go 语言实现(Go implementation)提供的一致性保证,并进一步指出该保证对 Go 语言实现的限制;在工程实践层面,描述使用同步原语确保 goroutine 间可见性的方法,并进一步指出常见的错误同步手法。

0%