C11多线程与原子
C11 是 C 语言正式拥抱多核时代的标志——引入了 标准线程库 <threads.h>、原子操作 <stdatomic.h> 与 内存模型,让 C 首次成为一门"线程感知"的语言。
一、多线程编程的核心问题
单线程程序的行为直观易懂:语句按顺序执行,一次读一次写。多线程加入后,数据竞争(data race) 和 可见性(visibility) 让一切复杂化。
数据竞争的定义(C11 5.1.2.4):
- 两个或更多线程
- 访问同一内存位置
- 至少一个是写
- 且未通过同步操作排序
数据竞争 → UB。C11 之前,C 甚至没有正式规定多线程语义!
二、C11 线程 API <threads.h>
#include <threads.h>
int worker(void *arg) {
int id = *(int *)arg;
printf("worker %d\n", id);
return 0;
}
int main(void) {
thrd_t t;
int arg = 42;
if (thrd_create(&t, worker, &arg) != thrd_success) return 1;
thrd_join(t, NULL);
return 0;
}
关键函数
| 函数 | 用途 |
|---|---|
thrd_create | 启动线程 |
thrd_join | 等待线程结束,回收资源 |
thrd_detach | 分离,无需 join |
thrd_exit | 退出当前线程 |
thrd_yield | 让出 CPU |
thrd_sleep | 睡眠 |
thrd_current | 获取当前线程 ID |
thrd_equal | 比较线程 ID |
互斥量 mtx_t
mtx_t mtx;
mtx_init(&mtx, mtx_plain);
mtx_lock(&mtx);
// 临界区
mtx_unlock(&mtx);
mtx_destroy(&mtx);
类型:
mtx_plain— 普通mtx_recursive— 递归(同线程可重复 lock)mtx_timed— 支持带超时- 可组合:
mtx_plain | mtx_recursive
条件变量 cnd_t
cnd_t cond;
mtx_t mtx;
int ready = 0;
// 生产者
mtx_lock(&mtx);
ready = 1;
cnd_signal(&cond);
mtx_unlock(&mtx);
// 消费者
mtx_lock(&mtx);
while (!ready) cnd_wait(&cond, &mtx);
mtx_unlock(&mtx);
永远用 while 循环检查条件——避免虚假唤醒(spurious wakeup)。
thread_local
#include <threads.h>
thread_local int per_thread_counter = 0; // C11 关键字(宏别名 _Thread_local)
每个线程独立拷贝。C23 中 thread_local 直接是关键字。
once_flag / call_once
一次性初始化:
once_flag flag = ONCE_FLAG_INIT;
void init(void) { /* one-time setup */ }
call_once(&flag, init); // 只有一个线程会执行 init
三、C11 线程 vs POSIX pthread
C11 <threads.h> 的语义模仿自 pthread。但存在两个现实:
- glibc 早期不支持
<threads.h>(直到 glibc 2.28 才完整实现,2018 年)。 - MSVC 早期不支持(直到 VS 2022 才对 C11 threads 有较好支持)。
因此:跨平台代码通常仍用 pthread(Unix)+ Win32 API(Windows),或第三方封装(tinycthread、c11threads)。
对比:
| C11 | POSIX pthread |
|---|---|
thrd_create | pthread_create |
thrd_join | pthread_join |
mtx_lock | pthread_mutex_lock |
cnd_wait | pthread_cond_wait |
call_once | pthread_once |
thread_local | __thread (GCC) / pthread_key_create |