stdatomic.h
<stdatomic.h> 是 C11 标准引入的头文件,它提供了原子类型和原子操作的支持。原子操作是不可分割的操作,在多线程环境中执行时不会被其他线程打断,从而避免数据竞争(data race)问题。它是 C 语言中实现无锁编程(lock-free programming)的基础设施。
引入头文件
#include <stdatomic.h>数据结构
// 原子布尔类型
typedef _Atomic _Bool atomic_flag;
// 原子整型
typedef _Atomic int atomic_int;
typedef _Atomic unsigned int atomic_uint;
typedef _Atomic long atomic_long;
typedef _Atomic unsigned long atomic_ulong;
typedef _Atomic short atomic_short;
typedef _Atomic unsigned short atomic_ushort;
typedef _Atomic char atomic_char;
typedef _Atomic unsigned char atomic_uchar;
typedef _Atomic long long atomic_llong;
typedef _Atomic unsigned long long atomic_ullong;
// 原子指针类型
typedef _Atomic intptr_t atomic_intptr_t;
typedef _Atomic uintptr_t atomic_uintptr_t;
typedef _Atomic size_t atomic_size_t;
typedef _Atomic ptrdiff_t atomic_ptrdiff_t;
// 初始化宏
#define ATOMIC_VAR_INIT(value)
#define ATOMIC_FLAG_INIT
// 内存序
typedef enum {
memory_order_relaxed,
memory_order_consume,
memory_order_acquire,
memory_order_release,
memory_order_acq_rel,
memory_order_seq_cst
} memory_order;
// 锁无关属性宏
#define ATOMIC_BOOL_LOCK_FREE
#define ATOMIC_CHAR_LOCK_FREE
#define ATOMIC_INT_LOCK_FREE
#define ATOMIC_LONG_LOCK_FREE
#define ATOMIC_POINTER_LOCK_FREE内存序
内存序(memory order)决定了原子操作对其他线程的可见性约束,是理解原子操作的关键概念。
| 内存序 | 描述 |
|---|---|
memory_order_relaxed | 无排序约束,仅保证原子性,不保证操作顺序的可见性 |
memory_order_consume | 数据依赖排序,保证当前操作之前的数据依赖操作对其他线程可见(C17 后建议避免使用) |
memory_order_acquire | 获取语义,保证当前操作之后的读/写不会被重排到此操作之前 |
memory_order_release | 释放语义,保证当前操作之前的读/写不会被重排到此操作之后 |
memory_order_acq_rel | 同时具有获取和释放语义,适用于 read-modify-write 操作 |
memory_order_seq_cst | 顺序一致性,最严格的约束,所有线程看到的操作顺序完全一致 |
获取-释放语义的典型使用场景:
- acquire:用于读操作(如
atomic_load),确保后续的读写不会被重排到该 load 之前 - release:用于写操作(如
atomic_store),确保之前的读写不会被重排到该 store 之后
atomic_init
初始化原子对象
/**
* 参数
* obj -- 指向原子对象的指针
* value -- 要设置的值
* 无返回值
*/
void atomic_init(volatile A *obj, C value)注意:atomic_init 不是原子操作,应在对象被其他线程访问之前调用,通常用于初始化阶段。
atomic_store
原子存储操作,将值写入原子对象
/**
* 参数
* obj -- 指向原子对象的指针
* desired -- 要存储的值
* 无返回值
*/
void atomic_store(volatile A *obj, C desired)
/**
* 显式指定内存序版本
* 参数
* obj -- 指向原子对象的指针
* desired -- 要存储的值
* order -- 内存序,有效值为 memory_order_relaxed, memory_order_release, memory_order_seq_cst
*/
void atomic_store_explicit(volatile A *obj, C desired, memory_order order)atomic_load
原子加载操作,从原子对象读取值
/**
* 参数
* obj -- 指向原子对象的指针
* 返回值
* 原子对象的当前值
*/
C atomic_load(volatile A *obj)
/**
* 显式指定内存序版本
* 参数
* obj -- 指向原子对象的指针
* order -- 内存序,有效值为 memory_order_relaxed, memory_order_acquire, memory_order_seq_cst
* 返回值
* 原子对象的当前值
*/
C atomic_load_explicit(volatile A *obj, memory_order order)atomic_exchange
原子交换操作,将新值写入原子对象并返回旧值。这是实现 TAS(Test-And-Set)自旋锁的核心原语。
/**
* 参数
* obj -- 指向原子对象的指针
* desired -- 要存储的新值
* 返回值
* 原子对象的旧值
*/
C atomic_exchange(volatile A *obj, C desired)
/**
* 显式指定内存序版本
*/
C atomic_exchange_explicit(volatile A *obj, C desired, memory_order order)示例
#include <stdio.h>
#include <stdatomic.h>
int main()
{
atomic_int value = ATOMIC_VAR_INIT(10);
int old = atomic_exchange(&value, 20);
printf("old: %d, new: %d\n", old, atomic_load(&value));
return 0;
}运行结果
$ gcc -std=c11 main.c -o main && ./main
old: 10, new: 20atomic_compare_exchange_strong
原子比较并交换操作(强版本)。如果原子对象的当前值等于 expected,则将其设置为 desired 并返回 true;否则将 expected 更新为原子对象的当前值并返回 false。
/**
* 参数
* obj -- 指向原子对象的指针
* expected -- 指向期望值的指针,若比较失败会被更新为当前值
* desired -- 要存储的新值
* 返回值
* 比较成功返回 true,失败返回 false
*/
_Bool atomic_compare_exchange_strong(volatile A *obj, C *expected, C desired)
/**
* 显式指定内存序版本
* 参数
* success -- 比较成功时使用的内存序
* failure -- 比较失败时使用的内存序
*/
_Bool atomic_compare_exchange_strong_explicit(volatile A *obj, C *expected, C desired,
memory_order success, memory_order failure)atomic_compare_exchange_weak
原子比较并交换操作(弱版本)。与强版本的区别在于:即使原子对象的当前值等于 expected,弱版本也允许虚假失败(spurious failure),即返回 false 并更新 expected。
弱版本在某些架构(如 ARM 的 LL/SC)上性能更好,通常用于循环中。
/**
* 参数
* obj -- 指向原子对象的指针
* expected -- 指向期望值的指针
* desired -- 要存储的新值
* 返回值
* 比较成功返回 true,失败(含虚假失败)返回 false
*/
_Bool atomic_compare_exchange_weak(volatile A *obj, C *expected, C desired)
/**
* 显式指定内存序版本
*/
_Bool atomic_compare_exchange_weak_explicit(volatile A *obj, C *expected, C desired,
memory_order success, memory_order failure)CAS 强弱版本对比
| 特性 | strong | weak |
|---|---|---|
| 虚假失败 | 不会 | 可能 |
| 适用场景 | 不在循环中使用时 | 在循环中使用时 |
| 性能 | 在 LL/SC 架构上可能额外开销 | 在 LL/SC 架构上更高效 |
atomic_fetch_add
原子加法操作,将值加到原子对象上并返回修改前的旧值
/**
* 参数
* obj -- 指向原子对象的指针
* arg -- 要加的值
* 返回值
* 修改前原子对象的旧值
*/
C atomic_fetch_add(volatile A *obj, M arg)
/**
* 显式指定内存序版本
*/
C atomic_fetch_add_explicit(volatile A *obj, M arg, memory_order order)示例
#include <stdio.h>
#include <stdatomic.h>
int main()
{
atomic_int counter = ATOMIC_VAR_INIT(0);
int old = atomic_fetch_add(&counter, 1);
printf("old: %d, current: %d\n", old, atomic_load(&counter));
old = atomic_fetch_add(&counter, 10);
printf("old: %d, current: %d\n", old, atomic_load(&counter));
return 0;
}运行结果
$ gcc -std=c11 main.c -o main && ./main
old: 0, current: 1
old: 1, current: 11atomic_fetch_sub
原子减法操作,从原子对象中减去值并返回修改前的旧值
/**
* 参数
* obj -- 指向原子对象的指针
* arg -- 要减的值
* 返回值
* 修改前原子对象的旧值
*/
C atomic_fetch_sub(volatile A *obj, M arg)
/**
* 显式指定内存序版本
*/
C atomic_fetch_sub_explicit(volatile A *obj, M arg, memory_order order)atomic_fetch_or
原子按位或操作,将原子对象与值进行按位或运算并返回修改前的旧值
/**
* 参数
* obj -- 指向原子对象的指针
* arg -- 按位或的值
* 返回值
* 修改前原子对象的旧值
*/
C atomic_fetch_or(volatile A *obj, M arg)
/**
* 显式指定内存序版本
*/
C atomic_fetch_or_explicit(volatile A *obj, M arg, memory_order order)atomic_fetch_and
原子按位与操作,将原子对象与值进行按位与运算并返回修改前的旧值
/**
* 参数
* obj -- 指向原子对象的指针
* arg -- 按位与的值
* 返回值
* 修改前原子对象的旧值
*/
C atomic_fetch_and(volatile A *obj, M arg)
/**
* 显式指定内存序版本
*/
C atomic_fetch_and_explicit(volatile A *obj, M arg, memory_order order)atomic_fetch_xor
原子按位异或操作,将原子对象与值进行按位异或运算并返回修改前的旧值
/**
* 参数
* obj -- 指向原子对象的指针
* arg -- 按位异或的值
* 返回值
* 修改前原子对象的旧值
*/
C atomic_fetch_xor(volatile A *obj, M arg)
/**
* 显式指定内存序版本
*/
C atomic_fetch_xor_explicit(volatile A *obj, M arg, memory_order order)atomic_flag_test_and_set
原子测试并设置操作,将 atomic_flag 设置为 true 并返回之前的值。这是最基础的原子操作原语,可用于实现自旋锁。
/**
* 参数
* obj -- 指向 atomic_flag 的指针
* 返回值
* 设置前 flag 的值
*/
_Bool atomic_flag_test_and_set(volatile atomic_flag *obj)
/**
* 显式指定内存序版本
*/
_Bool atomic_flag_test_and_set_explicit(volatile atomic_flag *obj, memory_order order)atomic_flag_clear
原子清除操作,将 atomic_flag 设置为 false
/**
* 参数
* obj -- 指向 atomic_flag 的指针
* 无返回值
*/
void atomic_flag_clear(volatile atomic_flag *obj)
/**
* 显式指定内存序版本
*/
void atomic_flag_clear_explicit(volatile atomic_flag *obj, memory_order order)atomic_is_lock_free
判断原子操作是否是无锁的
/**
* 参数
* obj -- 指向原子对象的指针
* 返回值
* 如果该类型的原子操作是无锁的返回非零值,否则返回 0
*/
_Bool atomic_is_lock_free(volatile A *obj)原子操作分类
| 类别 | 操作 | 说明 |
|---|---|---|
| 存储 | atomic_store | 写入值 |
| 加载 | atomic_load | 读取值 |
| 交换 | atomic_exchange | 写入新值,返回旧值(TAS 语义) |
| 比较交换 | atomic_compare_exchange_strong/weak | CAS 语义 |
| 算术 | atomic_fetch_add, atomic_fetch_sub | 原子加减 |
| 位运算 | atomic_fetch_or, atomic_fetch_and, atomic_fetch_xor | 原子位运算 |
| 标志 | atomic_flag_test_and_set, atomic_flag_clear | 最基础的原子原语 |
每个操作都有对应的 _explicit 版本,可显式指定内存序。
示例:原子计数器
#include <stdio.h>
#include <stdlib.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int counter = ATOMIC_VAR_INIT(0);
void *increment(void *arg)
{
int iterations = *(int *)arg;
for (int i = 0; i < iterations; i++)
{
atomic_fetch_add(&counter, 1);
}
return NULL;
}
int main()
{
int num_threads = 4;
int iterations = 100000;
pthread_t threads[num_threads];
for (int i = 0; i < num_threads; i++)
{
pthread_create(&threads[i], NULL, increment, &iterations);
}
for (int i = 0; i < num_threads; i++)
{
pthread_join(threads[i], NULL);
}
printf("counter: %d, expected: %d\n", atomic_load(&counter), num_threads * iterations);
return 0;
}运行结果
$ gcc -std=c11 -pthread main.c -o main && ./main
counter: 400000, expected: 400000示例:基于 TAS 的自旋锁
#include <stdio.h>
#include <stdlib.h>
#include <stdatomic.h>
#include <pthread.h>
typedef struct {
atomic_int flag;
} tas_spinlock_t;
void tas_spinlock_init(tas_spinlock_t *lock)
{
atomic_store(&lock->flag, 0);
}
void tas_spinlock_acquire(tas_spinlock_t *lock)
{
while (atomic_exchange(&lock->flag, 1) == 1)
{
}
}
void tas_spinlock_release(tas_spinlock_t *lock)
{
atomic_store(&lock->flag, 0);
}
int count = 0;
tas_spinlock_t lock;
void *run_task(void *arg)
{
for (int i = 0; i < 100000; i++)
{
tas_spinlock_acquire(&lock);
count++;
tas_spinlock_release(&lock);
}
return NULL;
}
int main()
{
const int nthread = 4;
pthread_t t[nthread];
tas_spinlock_init(&lock);
for (int i = 0; i < nthread; i++)
{
pthread_create(&t[i], NULL, run_task, NULL);
}
for (int i = 0; i < nthread; i++)
{
pthread_join(t[i], NULL);
}
printf("count: %d, expected: %d\n", count, nthread * 100000);
return 0;
}运行结果
$ gcc -std=c11 -pthread main.c -o main && ./main
count: 400000, expected: 400000示例:基于 CAS 的自旋锁
#include <stdio.h>
#include <stdlib.h>
#include <stdatomic.h>
#include <pthread.h>
typedef struct {
atomic_int flag;
} cas_spinlock_t;
void cas_spinlock_init(cas_spinlock_t *lock)
{
atomic_store(&lock->flag, 0);
}
void cas_spinlock_acquire(cas_spinlock_t *lock)
{
int expected = 0;
while (!atomic_compare_exchange_weak(&lock->flag, &expected, 1))
{
expected = 0;
}
}
void cas_spinlock_release(cas_spinlock_t *lock)
{
atomic_store(&lock->flag, 0);
}
int count = 0;
cas_spinlock_t lock;
void *run_task(void *arg)
{
for (int i = 0; i < 100000; i++)
{
cas_spinlock_acquire(&lock);
count++;
cas_spinlock_release(&lock);
}
return NULL;
}
int main()
{
const int nthread = 4;
pthread_t t[nthread];
cas_spinlock_init(&lock);
for (int i = 0; i < nthread; i++)
{
pthread_create(&t[i], NULL, run_task, NULL);
}
for (int i = 0; i < nthread; i++)
{
pthread_join(t[i], NULL);
}
printf("count: %d, expected: %d\n", count, nthread * 100000);
return 0;
}运行结果
$ gcc -std=c11 -pthread main.c -o main && ./main
count: 400000, expected: 400000示例:基于 atomic_flag 的自旋锁
#include <stdio.h>
#include <stdlib.h>
#include <stdatomic.h>
#include <pthread.h>
typedef struct {
atomic_flag flag;
} flag_spinlock_t;
void flag_spinlock_init(flag_spinlock_t *lock)
{
atomic_flag_clear(&lock->flag);
}
void flag_spinlock_acquire(flag_spinlock_t *lock)
{
while (atomic_flag_test_and_set(&lock->flag))
{
}
}
void flag_spinlock_release(flag_spinlock_t *lock)
{
atomic_flag_clear(&lock->flag);
}
int count = 0;
flag_spinlock_t lock;
void *run_task(void *arg)
{
for (int i = 0; i < 100000; i++)
{
flag_spinlock_acquire(&lock);
count++;
flag_spinlock_release(&lock);
}
return NULL;
}
int main()
{
const int nthread = 4;
pthread_t t[nthread];
flag_spinlock_init(&lock);
for (int i = 0; i < nthread; i++)
{
pthread_create(&t[i], NULL, run_task, NULL);
}
for (int i = 0; i < nthread; i++)
{
pthread_join(t[i], NULL);
}
printf("count: %d, expected: %d\n", count, nthread * 100000);
return 0;
}运行结果
$ gcc -std=c11 -pthread main.c -o main && ./main
count: 400000, expected: 400000示例:生产者-消费者(acquire/release 语义)
#include <stdio.h>
#include <stdatomic.h>
#include <pthread.h>
#include <unistd.h>
#define BUFFER_SIZE 8
int buffer[BUFFER_SIZE];
atomic_int produced = ATOMIC_VAR_INIT(0);
atomic_int consumed = ATOMIC_VAR_INIT(0);
void *producer(void *arg)
{
for (int i = 1; i <= 20; i++)
{
int pos;
while ((pos = atomic_load(&produced) - atomic_load(&consumed)) >= BUFFER_SIZE)
{
}
buffer[atomic_load(&produced) % BUFFER_SIZE] = i;
atomic_store_explicit(&produced, atomic_load(&produced) + 1, memory_order_release);
printf("produced: %d\n", i);
}
return NULL;
}
void *consumer(void *arg)
{
for (int i = 1; i <= 20; i++)
{
while (atomic_load_explicit(&produced, memory_order_acquire) <= atomic_load(&consumed))
{
}
int val = buffer[atomic_load(&consumed) % BUFFER_SIZE];
atomic_store(&consumed, atomic_load(&consumed) + 1);
printf("consumed: %d\n", val);
}
return NULL;
}
int main()
{
pthread_t prod, cons;
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
pthread_join(prod, NULL);
pthread_join(cons, NULL);
return 0;
}运行结果
$ gcc -std=c11 -pthread main.c -o main && ./main
produced: 1
produced: 2
consumed: 1
consumed: 2
...