目录
正在加载目录…
正在阅读专栏 OSTEP 操作系统专栏 第 22 篇 · 共 62 篇 · 35%

OSTEP:Lock-based Concurrent Data Structures

发布于 2026-09-17 21:40 · 最后编辑于 2026-09-17 22:08 · 版本 v2 · 字数 11,159 · 预计阅读 23 分钟 👁 15 次阅读

OSTEP:Lock-based Concurrent Data Structures

本篇对应 OSTEP Version 1.10 的 “Lock-based Concurrent Data Structures”。为 data structure 加 lock 能使其 thread safe,但 lock 的位置与粒度同时决定 correctness 和 performance。

类型与定位

  • 笔记类型:深度分析
  • 翻译基准:官方 threads-locks-usage.pdf,Version 1.10。
  • 图件说明:原文的 counter trace、list/queue code 与性能对比按原位置保留为代码块、表格和 Mermaid;没有独立 raster image。

TL;DR

  • 最简单的 thread-safe data structure 是在每个 public operation 外围加一把 lock。
  • “正确”不等于“可扩展”:单一全局 lock 会让多 CPU 上的 contention 成为瓶颈。
  • approximate counter 用 per-CPU local counters 换取 scalability,代价是读数暂时不精确。
  • linked list 需要特别注意 error path,避免 malloc 失败时忘记 unlock;hand-over-hand locking 理论上并发更高,但 lock 开销可能抵消收益。
  • queue 可用 head/tail 两把 lock 和 dummy node 让 enqueue 与 dequeue 并行。

目录

章节内容
设计目标thread safety 与 scalability
Concurrent counter粗粒度与 approximate counter
Concurrent linked listerror path 与 lock coupling
Concurrent queuehead/tail locks 与 dummy node
设计原则测量而非猜测

设计目标

给定一个 data structure,添加 lock 时要同时回答:

  1. 哪些字段构成 shared state?
  2. 哪些操作必须 atomic?
  3. 哪些代码必须在 critical section 内?
  4. 如何减少 lock contention,让多个 threads 尽可能并行访问?

把 lock 加到 data structure 后,它变成 thread safe;但具体加法决定了吞吐量和可扩展性。更多 concurrency 不一定更快,额外 lock acquire/release 本身也有成本。

Concurrent counter

最简单的 counter 是一个 shared integer:

c
typedef struct __counter_t {
    int value;
} counter_t;

void increment(counter_t *c) { c->value++; }
void decrement(counter_t *c) { c->value--; }
int get(counter_t *c) { return c->value; }

单一 lock

c
typedef struct __counter_t {
    int value;
    pthread_mutex_t lock;
} counter_t;

void increment(counter_t *c) {
    Pthread_mutex_lock(&c->lock);
    c->value++;
    Pthread_mutex_unlock(&c->lock);
}

这种方案简单而且正确,但所有 updates 都竞争同一把 lock。一个线程时可能很快,多线程在多个 CPUs 上运行时却可能严重 slowdown;理想的 perfect scaling 是工作量增加但完成时间不增加。

Approximate counter

approximate counter 用每个 CPU 一个 local counter,再加一个 global counter:

mermaid
flowchart LR
  A[Thread on CPU 0] --> B[Local counter L0]
  C[Thread on CPU 1] --> D[Local counter L1]
  E[Thread on CPU 2] --> F[Local counter L2]
  B --> G[Global counter G]
  D --> G
  F --> G

thread 通常只更新自己 CPU 的 local counter,因此不同 CPUs 之间几乎没有 contention。当 local count 达到 threshold S 时,再持有 global lock,把 local value 批量转移到 global counter 并清零 local counter。

threshold S精确度scalability
小global value 更及时较差,频繁转移
大global value 可能滞后较好,转移较少

global count 最多可能落后约“CPU 数 × S”。这不是 bug,而是 accuracy/performance trade-off;如果业务允许近似统计,收益可能很大。

Concurrent linked list

最直接的 linked list 方案是在 insert、lookup 等 operation 入口加一把 list lock,在返回前释放:

c
typedef struct __list_t {
    node_t *head;
    pthread_mutex_t lock;
} list_t;

int List_Insert(list_t *L, int key) {
    pthread_mutex_lock(&L->lock);
    node_t *new = malloc(sizeof(node_t));
    if (new == NULL) {
        perror("malloc");
        pthread_mutex_unlock(&L->lock);
        return -1;
    }
    new->key = key;
    new->next = L->head;
    L->head = new;
    pthread_mutex_unlock(&L->lock);
    return 0;
}

这里 malloc 失败的 error path 也必须 unlock。更易维护的写法是把不访问 shared list 的 malloc 放在 lock 外,只在更新 head 的实际 critical section 中持锁;lookup 则用统一的 exit path,避免多个 return 分支漏掉 unlock。

Hand-over-hand locking

lock coupling 为每个 node 设置一把 lock。遍历时先获得 next node 的 lock,再释放 current node 的 lock:

mermaid
flowchart LR
  A[Lock node A] --> B[Lock node B]
  B --> C[Unlock node A]
  C --> D[Move to node B]

它允许多个 threads 同时遍历不同区域,但每个 node 都 acquire/release lock 的成本很高。实践中,一个简单的 single lock 可能比理论并行度更高的 hand-over-hand 方案更快;必须用 benchmark 验证。

Concurrent queue

Michael-Scott 风格的 lock-based queue 使用 head lock 和 tail lock,让 enqueue 与 dequeue 在常见路径上并行:

c
typedef struct __queue_t {
    node_t *head;
    node_t *tail;
    pthread_mutex_t head_lock, tail_lock;
} queue_t;

初始化时放入一个 dummy node,让 head 和 tail 从同一个节点开始。enqueue 主要持有 tail lock,dequeue 主要持有 head lock;dummy node 简化了空队列和首尾分离的边界处理。

mermaid
flowchart LR
  A[head lock] --> B[dequeue side]
  C[tail lock] --> D[enqueue side]
  B --> E[Dummy / linked nodes]
  D --> E

如果需要 bounded queue,并在 empty/full 时让 thread 睡眠,就不能只依赖这两把 lock,还需要 condition variables;见 OSTEP:Condition Variables。

源文档逐段补充

从最简单的正确版本开始

给 data structure 加 concurrency 的核心问题是:哪些 shared state 必须一起保持不变量,以及如何在正确性与 parallelism 之间取舍。最简单的设计是每个 public operation 入口 acquire 一把 lock,return 前 release;它类似 monitor,先确保结构 thread safe,再根据真实 benchmark 判断是否需要优化。如果简单方案已经足够快,就不应为了“看起来更并发”而增加复杂度。

Counter 的 scalability 示例

原文 benchmark 让每个 thread 对同一个 counter increment 一百万次,并把 thread 数从 1 增加到 4。单一 precise counter 在一条 thread 时约需 0.03 秒;两条 thread 同时更新时,由于所有 increment 都争抢同一 mutex,时间可能上升到 5 秒以上,继续增加 thread 只会更差。理想的 perfect scaling 是工作量增加但完成时间基本不增加,因为新增 CPU 可以并行处理新增工作。

approximate counter 为每个 CPU core 保存一个 local counter 与 local lock,并使用一个 global counter/global lock。通常 thread 只更新所在 CPU 的 local counter;当 local count 达到 threshold S 时,才取得 global lock,批量转移 local value 并清零。S 越小,global count 越精确但全局竞争越频繁;S 越大,scalability 越好但读数滞后最多约 NUMCPUS × S。

text
S = 5
L1: 0 → 1 → 2 → 3 → 4 → 5 → transfer to G, reset to 0
G:  0 → 5

如果每个 core 只有一个 thread,local lock 可以省略;原文实现保留它,是因为现实中一个 core 上可能有多个 thread。要得到 exact value,可以取得所有 local locks 再读取 global 与 locals,但这会重新引入严重 contention,因此 get() 通常返回 approximate global value。

不要预设更多 concurrency 一定更快

更细的 lock 可能带来更高 parallelism,也可能因为频繁 acquire/release、cache-coherence、复杂 control flow 和额外 memory traffic 而更慢。唯一可靠的方法是实现 simple 与 optimized 两个版本,在目标 workload 上测量。性能优化应在问题真实存在之后进行。

Linked list 的 error path

最初的 list implementation 在 List_Insert() 一开始加 lock,再 malloc node;若 malloc 失败,必须先 unlock 才能 return。Linux kernel patch 的研究显示,大量 bug 出现在这种 rarely-taken error path 中,因为函数在多个 return 前需要正确撤销已经完成的 stateful operation。

更安全的重写方式是:若 malloc 本身已经是 thread safe,就先在 lock 外分配和初始化 node,成功后只在更新 shared head 时持锁。List_Lookup() 则使用单一 return path:用局部 rv 保存成功/失败,跳出循环后统一 unlock,再 return。减少 lock acquire/release 与分支出口,既缩短 critical section,也降低遗漏 unlock 的机会。

Hand-over-hand locking 的实际取舍

lock coupling 为每个 node 设置 lock。遍历时先 acquire next node,再 release current node,确保链表连接处始终有一个受保护的 hand-over-hand 链:

text
hold A → acquire B → release A → acquire C → release B → ...

它允许多个 thread 同时遍历链表的不同部分,但每一步都需要 lock operation。即使链表很长、thread 很多,这些 lock overhead 也可能超过并发收益;也可以研究“每隔若干 nodes 才换 lock”的 hybrid,但必须先用 benchmark 证明需要它。

设计上还要避免 control-flow error:持锁后遇到 return、exit、allocation failure 或异常时,所有已取得的 lock 和其他临时 state 都必须按正确顺序释放。统一 cleanup path 往往比在每个分支中手写 unlock 更可靠。

Michael–Scott lock-based queue

queue 的简单方案是用一把大 lock;更具并发性的 Michael–Scott 方案将 head 与 tail 分开保护。enqueue 的常见路径只访问 tail_lock,dequeue 只访问 head_lock,因此二者可以并行。

初始化时分配一个 dummy node,让 head 和 tail 都指向它。dequeue 取 dummy 的 next 作为真正的首 node;空队列只需检查 next == NULL。dummy node 把 empty、首尾分离等边界情况统一起来,减少特殊分支。

c
void Queue_Enqueue(queue_t *q, int value) {
    node_t *tmp = malloc(sizeof(node_t));
    assert(tmp != NULL);
    tmp->value = value;
    tmp->next = NULL;
    pthread_mutex_lock(&q->tail_lock);
    q->tail->next = tmp;
    q->tail = tmp;
    pthread_mutex_unlock(&q->tail_lock);
}

仅有 locks 的 queue 在 empty 时通常返回失败;如果要求 producer 在 full 时等待、consumer 在 empty 时等待,还需要 condition variables 来表达 blocking semantics。

Concurrent hash table

可以把前面实现的 concurrent list 作为 hash table 的 bucket:

c
#define BUCKETS 101

typedef struct {
    list_t lists[BUCKETS];
} hash_t;

int Hash_Insert(hash_t *H, int key) {
    return List_Insert(&H->lists[key % BUCKETS], key);
}

每个 bucket 拥有自己的 list lock,而不是让整个 hash table 共用一把 lock。不同 key 落入不同 bucket 时,多个 insert/lookup 可以并行;代价是 hash distribution、bucket 数量、resize 和跨 bucket operation 都需要额外设计。原文的 concurrent updates benchmark 显示,这种 per-bucket locking 的 hash table 随 thread/workload 增加仍能较好扩展,而 single-lock linked list 很快成为瓶颈。

从 lock-based 到 non-blocking

本篇只覆盖 lock-based structure;更高性能的设计还包括 lock-free/non-blocking structure、并发 B-tree 和其他专用算法。它们可能减少 blocking,却会引入 atomic memory reclamation、ABA、memory ordering 等更复杂问题。学习路径应从正确的 single-lock 版本开始,再通过 measurement 判断是否值得进入这些领域。

Code homework 的测量目标

原文练习要求用 gettimeofday() 或 x86 rdtsc 测量:simple counter 随 thread 数变化的时间、approximate counter 随 thread 数和 threshold 变化的时间、hand-over-hand list 与 single-lock list 的对比,以及一种自选 data structure 在简单和复杂 locking strategy 下的差异。关键问题是确认 timer 精度、CPU 数量对结果的影响,并把性能变化归因到 contention、lock overhead 和 locality,而非只记录一个最终数字。

官方 Code Homework:并发结构的实现与测量

原文的 Code Homework 以“正确实现后再测量”为主线,要求记录环境、参数和结果,而不是只凭直觉判断哪种 locking strategy 更快:

  1. 在程序中使用 gettimeofday() 重新完成本章的计时。测量这个 timer 的精度和能够区分的最小时间间隔;也可以研究 x86 的 cycle counter(rdtsc)。
  2. 实现 simple concurrent counter,测量 increment 大量次数时,thread 数增加对运行时间的影响;记录测试机器有多少 CPUs,并判断 CPU 数量是否影响结果。
  3. 实现 approximate counter,分别改变 thread 数与 threshold,测量 performance,并与本章的结果比较。
  4. 阅读 Moir 与 Shavit 的 survey,实现 hand-over-hand locking 的 linked list,测量它何时优于本章的 standard single-lock list。
  5. 选择一个更有趣的 data structure(例如 B-tree),先用 single lock 实现,测量 concurrent threads 增加时的 performance。
  6. 为这个 data structure 设计一种更复杂的 locking strategy,实现并测量;与 straightforward single-lock 方案比较,说明收益是否抵消了额外复杂度。

如何解释测量结果

  • 先确认计时器、CPU 数和 compiler/build flags,避免把 measurement artifact 当作 lock 的性质。
  • 分别记录 uncontended、single-CPU contention 和 multi-CPU contention;它们对应的瓶颈可能完全不同。
  • 对 approximate counter 同时记录运行时间与误差范围,因为 throughput 提升是以读数暂时不精确为代价的。
  • hand-over-hand locking 若没有明显胜出,并不表示实现失败;每个 node 的 lock acquire/release、cache movement 与 pointer traversal 可能已经超过减少 contention 带来的收益。
  • 复杂 locking strategy 只有在真实 workload 上更快且仍然容易证明正确时才值得保留。

本章小结

构造 lock-based concurrent data structure 时,最可靠的路径是先给整个结构加一把清晰的 global lock,证明不变量和 error path 正确,再根据 benchmark 定位瓶颈。approximate counter、per-node list locks、head/tail queue locks 与 per-bucket hash locks 展示了逐步增加 concurrency 的方法;但更多 locks 不自动带来更好 performance,反而会增加 lock overhead、cache traffic、control-flow bug 和 deadlock 风险。

OSTEP 也特别提醒避免 premature optimization:如果 simple design 已经满足目标,就没有理由为了“看起来更并发”而引入复杂实现。只有当 measurement 证明 single-lock design 是瓶颈时,才应针对具体 data structure 和 workload 做优化。

设计原则

  • 先实现清楚且正确的 coarse-grained 版本;
  • 只锁定真正修改 shared state 的区域;
  • 统一处理 failure/return path;
  • 使用不同 locks 前先定义锁顺序,避免 deadlock;
  • 用真实 workload 测量,不要因为“更多并发”就假设性能更好。

与已有笔记的关系

参考资料

原文逐段补充

CRUX:HOW TO ADD LOCKS TO DATA STRUCTURES

给定一个 data structure,应该如何添加 locks,才能使它正确工作?进一步,如何添加 locks,才能让许多 threads 同时访问它并获得较高 performance?本章只提供一个 introduction;这个主题已有数千篇研究论文,Moir 与 Shavit 的 survey [MS04] 是进一步学习的好起点。

29.1 Concurrent Counters:Figure 29.1–29.6

没有同步的 counter:

c
typedef struct __counter_t {
    int value;
} counter_t;

void init(counter_t *c) { c->value = 0; }
void increment(counter_t *c) { c->value++; }
void decrement(counter_t *c) { c->value--; }
int get(counter_t *c) { return c->value; }

使用 single lock 的 precise counter:

c
typedef struct __counter_t {
    int value;
    pthread_mutex_t lock;
} counter_t;

void init(counter_t *c) {
    c->value = 0;
    Pthread_mutex_init(&c->lock, NULL);
}

void increment(counter_t *c) {
    Pthread_mutex_lock(&c->lock);
    c->value++;
    Pthread_mutex_unlock(&c->lock);
}

void decrement(counter_t *c) {
    Pthread_mutex_lock(&c->lock);
    c->value--;
    Pthread_mutex_unlock(&c->lock);
}

int get(counter_t *c) {
    Pthread_mutex_lock(&c->lock);
    int rc = c->value;
    Pthread_mutex_unlock(&c->lock);
    return rc;
}

原文 benchmark 在一台四核 2.7 GHz Intel i5 iMac 上,让每个 thread 更新 counter 一百万次。single thread 约需 0.03 秒;两个 threads 各更新一百万次时,precise counter 可能超过 5 秒,增加 threads 后更差。这与 perfect scaling 相反:理想情况下工作量增加,但新增 CPU 并行处理后完成时间不应增加。

approximate counter 的原文实现:

c
typedef struct __counter_t {
    int global;                  // global count
    pthread_mutex_t glock;       // global lock
    int local[NUMCPUS];          // per-CPU count
    pthread_mutex_t llock[NUMCPUS];
    int threshold;               // update frequency
} counter_t;

void init(counter_t *c, int threshold) {
    c->threshold = threshold;
    c->global = 0;
    pthread_mutex_init(&c->glock, NULL);
    int i;
    for (i = 0; i < NUMCPUS; i++) {
        c->local[i] = 0;
        pthread_mutex_init(&c->llock[i], NULL);
    }
}

void update(counter_t *c, int threadID, int amt) {
    int cpu = threadID % NUMCPUS;
    pthread_mutex_lock(&c->llock[cpu]);
    c->local[cpu] += amt;
    if (c->local[cpu] >= c->threshold) {
        pthread_mutex_lock(&c->glock);
        c->global += c->local[cpu];
        pthread_mutex_unlock(&c->glock);
        c->local[cpu] = 0;
    }
    pthread_mutex_unlock(&c->llock[cpu]);
}

int get(counter_t *c) {
    pthread_mutex_lock(&c->glock);
    int val = c->global;
    pthread_mutex_unlock(&c->glock);
    return val; // only approximate!
}

Figure 29.3 的一个 trace(threshold S = 5)是:

TimeL1L2L3L4G
000000
100110
210210
320310
430320
541330
602345(从 L1 transfer)
7024010(从 L4 transfer)

原文 Figure 29.5 对比 precise/approximate counter 的 time,Figure 29.6 则固定四个 threads、每个 increment 一百万次,改变 threshold S = 1, 2, 4, …, 1024。S 越小,global count 越准确但 transfer 越频繁;S 越大,performance 越好但 global count 最多滞后 NUMCPUS × S。如果每个 CPU 只有一个 thread,local lock 可以省略;原文保留它是因为一个 core 上可能有多个 threads。

原文 Figure 29.5 是性能折线图;以下表格保留其坐标轴、系列和趋势(对于图中未标注的精确数值不作臆造):

横轴纵轴PreciseApproximate
Threads = 1–4Time(seconds)线程数增加后显著上升,2 threads 后进入 5 秒以上量级从 1 到 4 threads 仅小幅增加

Figure 29.6 固定 4 threads、每个 thread increment 一百万次,在 S = 1, 2, 4, …, 1024 上观察 time:

横轴纵轴主要趋势
Approximation Factor S(1–1024)Time(seconds)S 越大,global transfer 越少,运行时间整体下降并趋于稳定
S 较小global-count accuracy更接近精确值,但全局 lock contention 更高
S 较大global-count accuracy性能更好,但 global count 最多滞后 NUMCPUS × S

TIP:MORE CONCURRENCY ISN’T NECESSARILY FASTER

如果更并发的方案频繁 acquire/release locks,额外 overhead 可能抵消并发收益。正确方法是同时构建 simple 与 complex 两种方案并测量;performance 不能靠想象,方案要么更快,要么不是。

29.2 Concurrent Linked Lists:Figure 29.7–29.8

基础 single-lock list:

c
typedef struct __node_t {
    int key;
    struct __node_t *next;
} node_t;

typedef struct __list_t {
    node_t *head;
    pthread_mutex_t lock;
} list_t;

void List_Init(list_t *L) {
    L->head = NULL;
    pthread_mutex_init(&L->lock, NULL);
}

int List_Insert(list_t *L, int key) {
    pthread_mutex_lock(&L->lock);
    node_t *new = malloc(sizeof(node_t));
    if (new == NULL) {
        perror("malloc");
        pthread_mutex_unlock(&L->lock);
        return -1;
    }
    new->key = key;
    new->next = L->head;
    L->head = new;
    pthread_mutex_unlock(&L->lock);
    return 0;
}

int List_Lookup(list_t *L, int key) {
    pthread_mutex_lock(&L->lock);
    node_t *curr = L->head;
    while (curr) {
        if (curr->key == key) {
            pthread_mutex_unlock(&L->lock);
            return 0;
        }
        curr = curr->next;
    }
    pthread_mutex_unlock(&L->lock);
    return -1;
}

更安全的重写:malloc 假设自身 thread safe,因此移到 lock 外;lookup 使用共同的 exit path:

c
int List_Insert(list_t *L, int key) {
    node_t *new = malloc(sizeof(node_t));
    if (new == NULL) {
        perror("malloc");
        return -1;
    }
    new->key = key;
    pthread_mutex_lock(&L->lock);
    new->next = L->head;
    L->head = new;
    pthread_mutex_unlock(&L->lock);
    return 0;
}

int List_Lookup(list_t *L, int key) {
    int rv = -1;
    pthread_mutex_lock(&L->lock);
    node_t *curr = L->head;
    while (curr) {
        if (curr->key == key) {
            rv = 0;
            break;
        }
        curr = curr->next;
    }
    pthread_mutex_unlock(&L->lock);
    return rv;
}

原文指出,Linux kernel patches 中近 40% 的 bugs 出现在 rarely-taken error paths;因此 lock、allocation 和 return 的 control flow 应尽量简单,并确保每条 failure path 都撤销此前取得的 state。

TIP:BE WARY OF LOCKS AND CONTROL FLOW

很多 function 一开始 acquire lock、allocate memory 或执行其他 stateful operation;发生 error 时必须撤销全部 state,极易遗漏。应尽量减少这种复杂的 control-flow pattern。

29.3 Concurrent Queues 与 29.4 Concurrent Hash Table:Figure 29.9–29.11

Michael–Scott queue 的完整 lock-based 版本:

c
typedef struct __node_t {
    int value;
    struct __node_t *next;
} node_t;

typedef struct __queue_t {
    node_t *head;
    node_t *tail;
    pthread_mutex_t head_lock, tail_lock;
} queue_t;

void Queue_Init(queue_t *q) {
    node_t *tmp = malloc(sizeof(node_t));
    tmp->next = NULL;
    q->head = q->tail = tmp; // dummy node
    pthread_mutex_init(&q->head_lock, NULL);
    pthread_mutex_init(&q->tail_lock, NULL);
}

void Queue_Enqueue(queue_t *q, int value) {
    node_t *tmp = malloc(sizeof(node_t));
    assert(tmp != NULL);
    tmp->value = value;
    tmp->next = NULL;
    pthread_mutex_lock(&q->tail_lock);
    q->tail->next = tmp;
    q->tail = tmp;
    pthread_mutex_unlock(&q->tail_lock);
}

int Queue_Dequeue(queue_t *q, int *value) {
    pthread_mutex_lock(&q->head_lock);
    node_t *tmp = q->head;
    node_t *new_head = tmp->next;
    if (new_head == NULL) {
        pthread_mutex_unlock(&q->head_lock);
        return -1; // queue was empty
    }
    *value = new_head->value;
    q->head = new_head;
    pthread_mutex_unlock(&q->head_lock);
    free(tmp);
    return 0;
}

head lock 与 tail lock 让 enqueue/dequeue 在 common case 并行;dummy node 则分离 head 与 tail 的操作并简化 empty 边界。若要让 bounded queue 在 empty/full 时等待,需要 condition variables,而不只是这两把 locks。

以 concurrent list 为 bucket 的 hash table:

c
#define BUCKETS (101)

typedef struct __hash_t {
    list_t lists[BUCKETS];
} hash_t;

void Hash_Init(hash_t *H) {
    for (int i = 0; i < BUCKETS; i++)
        List_Init(&H->lists[i]);
}

int Hash_Insert(hash_t *H, int key) {
    return List_Insert(&H->lists[key % BUCKETS], key);
}

int Hash_Lookup(hash_t *H, int key) {
    return List_Lookup(&H->lists[key % BUCKETS], key);
}

每个 bucket 使用自己的 list lock,因此不同 buckets 上的 operations 可以并行。原文 Figure 29.11 对四个 CPUs 上每个 thread 10,000–50,000 次 concurrent updates 进行比较:single-lock list 很快成为 bottleneck,而这个简单的 per-bucket hash table 具有明显更好的 scaling;本版本不处理 resize,resizing 留作练习。

Figure 29.11 的横轴是每个 thread 的 inserts(Thousands,0–40),纵轴是 time(seconds,0–15),比较两个 series:

data structure随 inserts 增加的趋势结论
Simple Concurrent Listtime 快速上升,逐渐成为 bottlenecksingle lock 限制并发
Concurrent Hash Tabletime 增长很小,曲线明显更平per-bucket locks 提供更好的 scaling

TIP:AVOID PREMATURE OPTIMIZATION(KNUTH’S LAW)

先使用 single big lock 构建最基本且正确的 data structure;只有 measurement 证明它存在 performance problem 时才细化。Knuth 的名言是:“Premature optimization is the root of all evil。”Linux 早期也曾使用 big kernel lock(BKL),直到 multi-CPU 成为常态后,single lock 才成为 kernel scalability bottleneck。

29.5 Summary:源文档收束

本章从 counter、linked list、queue 讲到常用的 hash table,得到几条原则:必须小心处理 lock acquisition/release 与 control flow;增加 concurrency 不一定提高 performance;只有在 performance problem 真实存在时才应修复它,不能为了“更快”而提前引入复杂性。更高性能的 concurrent data structure(例如 B-tree)以及完全不使用 traditional locks 的 non-blocking data structure,都需要进一步学习。

源文档核对记录

  • 官方源文档:threads-locks-usage.pdf,Version 1.10,共 16 页。
  • 已核对源章节:29.1–29.5。
  • 已核对图件:Figure 29.1–29.11;代码图保留为 code block,性能图的坐标轴、系列和趋势按原位置转换为表格。
  • 原文没有需要单独下载的 raster image;Figure 29.5、29.6、29.11 是性能曲线,已用表格保留其可读语义。

References

  • [B+10] Silas Boyd-Wickizer 等,《An Analysis of Linux Scalability to Many Cores》,OSDI ’10:Linux multicore scalability 与 scalable counter。
  • [BH73] Per Brinch Hansen,《Operating System Principles》,Prentice-Hall,1973:早期关于 monitor 的著作。
  • [BC05] Daniel P. Bovet、Marco Cesati,《Understanding the Linux Kernel》,O’Reilly,2005。
  • [C06] Jonathan Corbet,《The Search For Fast, Scalable Counters》,2006;LWN。
  • [L+13] Lanyue Lu 等,《A Study of Linux File System Evolution》,FAST ’13。
  • [MS98] M. Michael、M. Scott,《Nonblocking Algorithms and Preemption-safe Locking on Multiprogrammed Shared-memory Multiprocessors》,Journal of Parallel and Distributed Computing,51(1),1998。
  • [MS04] Mark Moir、Nir Shavit,《Concurrent Data Structures》,2004;survey。
  • [MM00] Jim Mauro、Richard McDougall,《Solaris Internals: Core Kernel Architecture》,Prentice Hall,2000。
  • [S+11] Swaminathan Sundararaman 等,《Making the Common Case the Only Case with Anticipatory Memory Allocation》,FAST ’11。
← 返回列表
← 上一篇 OSTEP:Locks 下一篇 → OSTEP:Condition Variables

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论