跳转到内容
标准库Zig 0.17.0官方原文
源码std/atomic.zig

第 1 行

std.atomic.assert

别名

第 6 行

别名目标 std.debug.assert

std.atomic.AtomicOrder

别名

第 4 行

别名目标 std.lang.AtomicOrder

std.atomic.builtin

常量

第 1 行

std.atomic.cache_line

常量

第 519 行

CPU 原子更新内存时的估计缓存行大小。 添加此大小的填充,或按此边界对齐,以免原子更新的 内存迫使附近非原子访问的内存缓存失效。

https://en.wikipedia.org/wiki/False_sharing https://github.com/golang/go/search?q=CacheLinePadSize

comptime_int

std.atomic.cacheLineForCpu

函数

第 430 行

pub fn cacheLineForCpu(cpu: std.Target.Cpu) u16

参数

cpu: std.Target.Cpu

std.atomic.Mutex

容器

第 526 行

无锁且只有一个所有者的资源。

字段

unlocked
locked

std.atomic.Mutex.tryLock

函数

第 530 行

pub fn tryLock(m: *Mutex) bool

参数

m: *Mutex

std.atomic.Mutex.unlock

函数

第 534 行

pub fn unlock(m: *Mutex) void

参数

m: *Mutex

std.atomic.noop

函数

第 149 行

fn noop(rc: *RefCount) void

参数

rc: *RefCount

std.atomic.ref

函数

第 131 行

fn ref(rc: *RefCount) void

参数

rc: *RefCount

std.atomic.RefCount

别名

第 129 行

别名目标 std.atomic

std.atomic.spinLoopHint

函数

第 355 行

告知处理器,调用方处于忙等待自旋循环中。

pub inline fn spinLoopHint() void

用法示例

test spinLoopHint {
    for (0..10) |_| {
        spinLoopHint();
    }
}

std.atomic.std

别名

第 3 行

别名目标 std

std.atomic.testing

别名

第 5 行

别名目标 std.testing

std.atomic.unref

函数

第 136 行

fn unref(rc: *RefCount) void

参数

rc: *RefCount

std.atomic.Value

类型函数

第 9 行

这是对原始值的轻量封装,用于避免意外的数据竞争。

pub fn Value(comptime T: type) type

参数

T: type

字段

raw: T

直接操作此字段时,必须注意避免数据竞争。

用法示例

test Value {
    const RefCount = struct {
        count: Value(usize),
        dropFn: *const fn (*RefCount) void,

        const RefCount = @This();

        fn ref(rc: *RefCount) void {
            // 无需同步,仅更新计数器。
            _ = rc.count.fetchAdd(1, .monotonic);
        }

        fn unref(rc: *RefCount) void {
            // release 确保 unref() 之前的代码先发生于
            // 计数递减,因为届时可能调用 dropFn。
            if (rc.count.fetchSub(1, .release) == 1) {
                // 计数器值为 1 表示其他 unref() 已经发生,
                // 但不意味着每次 unref() 之前的使用都已可见。
                // 此加载获取先前 unref() 创建的释放序列,
                // 从而确保丢弃前这些使用操作可见。
                _ = rc.count.load(.acquire);
                (rc.dropFn)(rc);
            }
        }

        fn noop(rc: *RefCount) void {
            _ = rc;
        }
    };

    var ref_count: RefCount = .{
        .count = Value(usize).init(0),
        .dropFn = RefCount.noop,
    };
    ref_count.ref();
    ref_count.unref();
}

std.atomic.Value.Bit

类型

第 93 行

std.atomic.Value.bitReset

函数

第 107 行

标记为 inline,使 bit 在编译期已知时,可将此指令降级为更高效的机器码指令(如果可能)。

pub inline fn bitReset(self: *Self, bit: Bit, comptime order: AtomicOrder) u1

参数

self: *Self
bit: Bit
order: AtomicOrder

std.atomic.Value.bitSet

函数

第 98 行

标记为 inline,使 bit 在编译期已知时,可将此指令降级为更高效的机器码指令(如果可能)。

pub inline fn bitSet(self: *Self, bit: Bit, comptime order: AtomicOrder) u1

参数

self: *Self
bit: Bit
order: AtomicOrder

std.atomic.Value.bitToggle

函数

第 116 行

标记为 inline,使 bit 在编译期已知时,可将此指令降级为更高效的机器码指令(如果可能)。

pub inline fn bitToggle(self: *Self, bit: Bit, comptime order: AtomicOrder) u1

参数

self: *Self
bit: Bit
order: AtomicOrder

std.atomic.Value.cmpxchgStrong

函数

第 42 行

pub inline fn cmpxchgStrong( self: *Self, expected_value: T, new_value: T, comptime success_order: AtomicOrder, comptime fail_order: AtomicOrder, ) ?T

参数

self: *Self
expected_value: T
new_value: T
success_order: AtomicOrder
fail_order: AtomicOrder

std.atomic.Value.cmpxchgWeak

函数

第 32 行

pub inline fn cmpxchgWeak( self: *Self, expected_value: T, new_value: T, comptime success_order: AtomicOrder, comptime fail_order: AtomicOrder, ) ?T

参数

self: *Self
expected_value: T
new_value: T
success_order: AtomicOrder
fail_order: AtomicOrder

std.atomic.Value.fetchAdd

函数

第 52 行

pub inline fn fetchAdd(self: *Self, operand: T, comptime order: AtomicOrder) T

参数

self: *Self
operand: T
order: AtomicOrder

std.atomic.Value.fetchAnd

函数

第 68 行

pub inline fn fetchAnd(self: *Self, operand: T, comptime order: AtomicOrder) T

参数

self: *Self
operand: T
order: AtomicOrder

std.atomic.Value.fetchMax

函数

第 64 行

pub inline fn fetchMax(self: *Self, operand: T, comptime order: AtomicOrder) T

参数

self: *Self
operand: T
order: AtomicOrder

std.atomic.Value.fetchMin

函数

第 60 行

pub inline fn fetchMin(self: *Self, operand: T, comptime order: AtomicOrder) T

参数

self: *Self
operand: T
order: AtomicOrder

std.atomic.Value.fetchNand

函数

第 72 行

pub inline fn fetchNand(self: *Self, operand: T, comptime order: AtomicOrder) T

参数

self: *Self
operand: T
order: AtomicOrder

std.atomic.Value.fetchOr

函数

第 80 行

pub inline fn fetchOr(self: *Self, operand: T, comptime order: AtomicOrder) T

参数

self: *Self
operand: T
order: AtomicOrder

std.atomic.Value.fetchSub

函数

第 56 行

pub inline fn fetchSub(self: *Self, operand: T, comptime order: AtomicOrder) T

参数

self: *Self
operand: T
order: AtomicOrder

std.atomic.Value.fetchXor

函数

第 76 行

pub inline fn fetchXor(self: *Self, operand: T, comptime order: AtomicOrder) T

参数

self: *Self
operand: T
order: AtomicOrder

std.atomic.Value.init

函数

第 16 行

pub fn init(value: T) Self

参数

value: T

std.atomic.Value.load

函数

第 20 行

pub inline fn load(self: *const Self, comptime order: AtomicOrder) T

参数

self: *const Self
order: AtomicOrder

std.atomic.Value.rmw

函数

第 84 行

pub inline fn rmw( self: *Self, comptime op: std.builtin.AtomicRmwOp, operand: T, comptime order: AtomicOrder, ) T

参数

self: *Self
op: std.builtin.AtomicRmwOp
operand: T
order: AtomicOrder

std.atomic.Value.Self

别名

第 14 行

别名目标 std.atomic.Value

std.atomic.Value.store

函数

第 24 行

pub inline fn store(self: *Self, value: T, comptime order: AtomicOrder) void

参数

self: *Self
value: T
order: AtomicOrder

std.atomic.Value.swap

函数

第 28 行

pub inline fn swap(self: *Self, operand: T, comptime order: AtomicOrder) T

参数

self: *Self
operand: T
order: AtomicOrder
源码

std/atomic.zig

const builtin = @import("builtin");

const std = @import("std.zig");
const AtomicOrder = std.builtin.AtomicOrder;
const testing = std.testing;
const assert = std.debug.assert;

/// 这是对原始值的轻量封装,用于避免意外的数据竞争。
pub fn Value(comptime T: type) type {
    return extern struct {
        /// 直接操作此字段时,必须注意避免数据竞争。
        raw: T,

        const Self = @This();

        pub fn init(value: T) Self {
            return .{ .raw = value };
        }

        pub inline fn load(self: *const Self, comptime order: AtomicOrder) T {
            return @atomicLoad(T, &self.raw, order);
        }

        pub inline fn store(self: *Self, value: T, comptime order: AtomicOrder) void {
            @atomicStore(T, &self.raw, value, order);
        }

        pub inline fn swap(self: *Self, operand: T, comptime order: AtomicOrder) T {
            return @atomicRmw(T, &self.raw, .Xchg, operand, order);
        }

        pub inline fn cmpxchgWeak(
            self: *Self,
            expected_value: T,
            new_value: T,
            comptime success_order: AtomicOrder,
            comptime fail_order: AtomicOrder,
        ) ?T {
            return @cmpxchgWeak(T, &self.raw, expected_value, new_value, success_order, fail_order);
        }

        pub inline fn cmpxchgStrong(
            self: *Self,
            expected_value: T,
            new_value: T,
            comptime success_order: AtomicOrder,
            comptime fail_order: AtomicOrder,
        ) ?T {
            return @cmpxchgStrong(T, &self.raw, expected_value, new_value, success_order, fail_order);
        }

        pub inline fn fetchAdd(self: *Self, operand: T, comptime order: AtomicOrder) T {
            return @atomicRmw(T, &self.raw, .Add, operand, order);
        }

        pub inline fn fetchSub(self: *Self, operand: T, comptime order: AtomicOrder) T {
            return @atomicRmw(T, &self.raw, .Sub, operand, order);
        }

        pub inline fn fetchMin(self: *Self, operand: T, comptime order: AtomicOrder) T {
            return @atomicRmw(T, &self.raw, .Min, operand, order);
        }

        pub inline fn fetchMax(self: *Self, operand: T, comptime order: AtomicOrder) T {
            return @atomicRmw(T, &self.raw, .Max, operand, order);
        }

        pub inline fn fetchAnd(self: *Self, operand: T, comptime order: AtomicOrder) T {
            return @atomicRmw(T, &self.raw, .And, operand, order);
        }

        pub inline fn fetchNand(self: *Self, operand: T, comptime order: AtomicOrder) T {
            return @atomicRmw(T, &self.raw, .Nand, operand, order);
        }

        pub inline fn fetchXor(self: *Self, operand: T, comptime order: AtomicOrder) T {
            return @atomicRmw(T, &self.raw, .Xor, operand, order);
        }

        pub inline fn fetchOr(self: *Self, operand: T, comptime order: AtomicOrder) T {
            return @atomicRmw(T, &self.raw, .Or, operand, order);
        }

        pub inline fn rmw(
            self: *Self,
            comptime op: std.builtin.AtomicRmwOp,
            operand: T,
            comptime order: AtomicOrder,
        ) T {
            return @atomicRmw(T, &self.raw, op, operand, order);
        }

        const Bit = std.math.Log2Int(T);

        /// 标记为 `inline`,使 `bit` 在编译期已知时,可将此指令降级为更高效的机器码指令(如果可能)。
        ///
        ///
        pub inline fn bitSet(self: *Self, bit: Bit, comptime order: AtomicOrder) u1 {
            const mask = @as(T, 1) << bit;
            const value = self.fetchOr(mask, order);
            return @intFromBool(value & mask != 0);
        }

        /// 标记为 `inline`,使 `bit` 在编译期已知时,可将此指令降级为更高效的机器码指令(如果可能)。
        ///
        ///
        pub inline fn bitReset(self: *Self, bit: Bit, comptime order: AtomicOrder) u1 {
            const mask = @as(T, 1) << bit;
            const value = self.fetchAnd(~mask, order);
            return @intFromBool(value & mask != 0);
        }

        /// 标记为 `inline`,使 `bit` 在编译期已知时,可将此指令降级为更高效的机器码指令(如果可能)。
        ///
        ///
        pub inline fn bitToggle(self: *Self, bit: Bit, comptime order: AtomicOrder) u1 {
            const mask = @as(T, 1) << bit;
            const value = self.fetchXor(mask, order);
            return @intFromBool(value & mask != 0);
        }
    };
}

test Value {
    const RefCount = struct {
        count: Value(usize),
        dropFn: *const fn (*RefCount) void,

        const RefCount = @This();

        fn ref(rc: *RefCount) void {
            // 无需同步,仅更新计数器。
            _ = rc.count.fetchAdd(1, .monotonic);
        }

        fn unref(rc: *RefCount) void {
            // release 确保 unref() 之前的代码先发生于
            // 计数递减,因为届时可能调用 dropFn。
            if (rc.count.fetchSub(1, .release) == 1) {
                // 计数器值为 1 表示其他 unref() 已经发生,
                // 但不意味着每次 unref() 之前的使用都已可见。
                // 此加载获取先前 unref() 创建的释放序列,
                // 从而确保丢弃前这些使用操作可见。
                _ = rc.count.load(.acquire);
                (rc.dropFn)(rc);
            }
        }

        fn noop(rc: *RefCount) void {
            _ = rc;
        }
    };

    var ref_count: RefCount = .{
        .count = Value(usize).init(0),
        .dropFn = RefCount.noop,
    };
    ref_count.ref();
    ref_count.unref();
}

test "Value.swap" {
    var x = Value(usize).init(5);
    try testing.expectEqual(@as(usize, 5), x.swap(10, .seq_cst));
    try testing.expectEqual(@as(usize, 10), x.load(.seq_cst));

    const E = enum(usize) { a, b, c };
    var y = Value(E).init(.c);
    try testing.expectEqual(E.c, y.swap(.a, .seq_cst));
    try testing.expectEqual(E.a, y.load(.seq_cst));

    var z = Value(f32).init(5.0);
    try testing.expectEqual(@as(f32, 5.0), z.swap(10.0, .seq_cst));
    try testing.expectEqual(@as(f32, 10.0), z.load(.seq_cst));

    var a = Value(bool).init(false);
    try testing.expectEqual(false, a.swap(true, .seq_cst));
    try testing.expectEqual(true, a.load(.seq_cst));

    var b = Value(?*u8).init(null);
    try testing.expectEqual(@as(?*u8, null), b.swap(@as(?*u8, @ptrFromInt(@alignOf(u8))), .seq_cst));
    try testing.expectEqual(@as(?*u8, @ptrFromInt(@alignOf(u8))), b.load(.seq_cst));
}

test "Value.store" {
    var x = Value(usize).init(5);
    x.store(10, .seq_cst);
    try testing.expectEqual(@as(usize, 10), x.load(.seq_cst));
}

test "Value.cmpxchgWeak" {
    var x = Value(usize).init(0);

    try testing.expectEqual(@as(?usize, 0), x.cmpxchgWeak(1, 0, .seq_cst, .seq_cst));
    try testing.expectEqual(@as(usize, 0), x.load(.seq_cst));

    while (x.cmpxchgWeak(0, 1, .seq_cst, .seq_cst)) |_| {}
    try testing.expectEqual(@as(usize, 1), x.load(.seq_cst));

    while (x.cmpxchgWeak(1, 0, .seq_cst, .seq_cst)) |_| {}
    try testing.expectEqual(@as(usize, 0), x.load(.seq_cst));
}

test "Value.cmpxchgStrong" {
    var x = Value(usize).init(0);
    try testing.expectEqual(@as(?usize, 0), x.cmpxchgStrong(1, 0, .seq_cst, .seq_cst));
    try testing.expectEqual(@as(usize, 0), x.load(.seq_cst));
    try testing.expectEqual(@as(?usize, null), x.cmpxchgStrong(0, 1, .seq_cst, .seq_cst));
    try testing.expectEqual(@as(usize, 1), x.load(.seq_cst));
    try testing.expectEqual(@as(?usize, null), x.cmpxchgStrong(1, 0, .seq_cst, .seq_cst));
    try testing.expectEqual(@as(usize, 0), x.load(.seq_cst));
}

test "Value.fetchAdd" {
    var x = Value(usize).init(5);
    try testing.expectEqual(@as(usize, 5), x.fetchAdd(5, .seq_cst));
    try testing.expectEqual(@as(usize, 10), x.load(.seq_cst));
    try testing.expectEqual(@as(usize, 10), x.fetchAdd(std.math.maxInt(usize), .seq_cst));
    try testing.expectEqual(@as(usize, 9), x.load(.seq_cst));
}

test "Value.fetchSub" {
    var x = Value(usize).init(5);
    try testing.expectEqual(@as(usize, 5), x.fetchSub(5, .seq_cst));
    try testing.expectEqual(@as(usize, 0), x.load(.seq_cst));
    try testing.expectEqual(@as(usize, 0), x.fetchSub(1, .seq_cst));
    try testing.expectEqual(@as(usize, std.math.maxInt(usize)), x.load(.seq_cst));
}

test "Value.fetchMin" {
    var x = Value(usize).init(5);
    try testing.expectEqual(@as(usize, 5), x.fetchMin(0, .seq_cst));
    try testing.expectEqual(@as(usize, 0), x.load(.seq_cst));
    try testing.expectEqual(@as(usize, 0), x.fetchMin(10, .seq_cst));
    try testing.expectEqual(@as(usize, 0), x.load(.seq_cst));
}

test "Value.fetchMax" {
    var x = Value(usize).init(5);
    try testing.expectEqual(@as(usize, 5), x.fetchMax(10, .seq_cst));
    try testing.expectEqual(@as(usize, 10), x.load(.seq_cst));
    try testing.expectEqual(@as(usize, 10), x.fetchMax(5, .seq_cst));
    try testing.expectEqual(@as(usize, 10), x.load(.seq_cst));
}

test "Value.fetchAnd" {
    var x = Value(usize).init(0b11);
    try testing.expectEqual(@as(usize, 0b11), x.fetchAnd(0b10, .seq_cst));
    try testing.expectEqual(@as(usize, 0b10), x.load(.seq_cst));
    try testing.expectEqual(@as(usize, 0b10), x.fetchAnd(0b00, .seq_cst));
    try testing.expectEqual(@as(usize, 0b00), x.load(.seq_cst));
}

test "Value.fetchNand" {
    var x = Value(usize).init(0b11);
    try testing.expectEqual(@as(usize, 0b11), x.fetchNand(0b10, .seq_cst));
    try testing.expectEqual(~@as(usize, 0b10), x.load(.seq_cst));
    try testing.expectEqual(~@as(usize, 0b10), x.fetchNand(0b00, .seq_cst));
    try testing.expectEqual(~@as(usize, 0b00), x.load(.seq_cst));
}

test "Value.fetchOr" {
    var x = Value(usize).init(0b11);
    try testing.expectEqual(@as(usize, 0b11), x.fetchOr(0b100, .seq_cst));
    try testing.expectEqual(@as(usize, 0b111), x.load(.seq_cst));
    try testing.expectEqual(@as(usize, 0b111), x.fetchOr(0b010, .seq_cst));
    try testing.expectEqual(@as(usize, 0b111), x.load(.seq_cst));
}

test "Value.fetchXor" {
    var x = Value(usize).init(0b11);
    try testing.expectEqual(@as(usize, 0b11), x.fetchXor(0b10, .seq_cst));
    try testing.expectEqual(@as(usize, 0b01), x.load(.seq_cst));
    try testing.expectEqual(@as(usize, 0b01), x.fetchXor(0b01, .seq_cst));
    try testing.expectEqual(@as(usize, 0b00), x.load(.seq_cst));
}

test "Value.bitSet" {
    var x = Value(usize).init(0);

    for (0..@bitSizeOf(usize)) |bit_index| {
        const bit = @as(std.math.Log2Int(usize), @intCast(bit_index));
        const mask = @as(usize, 1) << bit;

        // 设置位应当改变该位
        try testing.expect(x.load(.seq_cst) & mask == 0);
        try testing.expectEqual(@as(u1, 0), x.bitSet(bit, .seq_cst));
        try testing.expect(x.load(.seq_cst) & mask != 0);

        // 再次设置此位不应改变它
        try testing.expectEqual(@as(u1, 1), x.bitSet(bit, .seq_cst));
        try testing.expect(x.load(.seq_cst) & mask != 0);

        // 之前的所有位都应保持不变(仍为置位状态)
        for (0..bit_index) |prev_bit_index| {
            const prev_bit = @as(std.math.Log2Int(usize), @intCast(prev_bit_index));
            const prev_mask = @as(usize, 1) << prev_bit;
            try testing.expect(x.load(.seq_cst) & prev_mask != 0);
        }
    }
}

test "Value.bitReset" {
    var x = Value(usize).init(0);

    for (0..@bitSizeOf(usize)) |bit_index| {
        const bit = @as(std.math.Log2Int(usize), @intCast(bit_index));
        const mask = @as(usize, 1) << bit;
        x.raw |= mask;

        // 清除此位应改变该位
        try testing.expect(x.load(.seq_cst) & mask != 0);
        try testing.expectEqual(@as(u1, 1), x.bitReset(bit, .seq_cst));
        try testing.expect(x.load(.seq_cst) & mask == 0);

        // 再次清除此位不应改变它
        try testing.expectEqual(@as(u1, 0), x.bitReset(bit, .seq_cst));
        try testing.expect(x.load(.seq_cst) & mask == 0);

        // 之前的所有位都应保持不变(仍为清零状态)
        for (0..bit_index) |prev_bit_index| {
            const prev_bit = @as(std.math.Log2Int(usize), @intCast(prev_bit_index));
            const prev_mask = @as(usize, 1) << prev_bit;
            try testing.expect(x.load(.seq_cst) & prev_mask == 0);
        }
    }
}

test "Value.bitToggle" {
    var x = Value(usize).init(0);

    for (0..@bitSizeOf(usize)) |bit_index| {
        const bit = @as(std.math.Log2Int(usize), @intCast(bit_index));
        const mask = @as(usize, 1) << bit;

        // 翻转此位应改变它
        try testing.expect(x.load(.seq_cst) & mask == 0);
        try testing.expectEqual(@as(u1, 0), x.bitToggle(bit, .seq_cst));
        try testing.expect(x.load(.seq_cst) & mask != 0);

        // 再次切换它*应当*改变该位
        try testing.expectEqual(@as(u1, 1), x.bitToggle(bit, .seq_cst));
        try testing.expect(x.load(.seq_cst) & mask == 0);

        // 此前的所有位都应保持不变(仍为再次翻转后的状态)
        for (0..bit_index) |prev_bit_index| {
            const prev_bit = @as(std.math.Log2Int(usize), @intCast(prev_bit_index));
            const prev_mask = @as(usize, 1) << prev_bit;
            try testing.expect(x.load(.seq_cst) & prev_mask == 0);
        }
    }
}

/// 告知处理器,调用方处于忙等待自旋循环中。
pub inline fn spinLoopHint() void {
    switch (builtin.target.cpu.arch) {
        // 空操作指令,可提示节省流水线或电力资源,
        // 或与硬件线程共享这些资源。
        // https://software.intel.com/content/www/us/en/develop/articles/benefitting-power-and-performance-sleep-loops.html
        .x86,
        .x86_64,
        => asm volatile ("pause"),

        // 空操作指令,用作让出硬件线程资源的提示。
        // https://stackoverflow.com/a/7588941
        .powerpc,
        .powerpcle,
        .powerpc64,
        .powerpc64le,
        => asm volatile ("or 27, 27, 27"),

        // 在常见 aarch64 CPU 上,`isb` 在释放执行资源方面
        // 似乎比 `yield` 更可靠。
        // https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8258604
        // https://bugs.mysql.com/bug.php?id=100664
        .aarch64,
        .aarch64_be,
        => asm volatile ("isb"),

        // https://www.keil.com/support/man/docs/armasm/armasm_dom1361289926796.htm
        .arm,
        .armeb,
        => if (comptime builtin.cpu.has(.arm, .has_v6k)) {
            asm volatile ("yield");
        },

        .thumb,
        .thumbeb,
        => if (comptime builtin.cpu.hasAny(.arm, &.{ .has_v6m, .thumb2 })) {
            asm volatile ("yield");
        },

        // 8 位立即数指定暂停的周期数。
        // 这里不宜对其取值施加过多限制。
        .hexagon,
        => asm volatile ("pause(#1)"),

        .mips,
        .mipsel,
        .mips64,
        .mips64el,
        => if (comptime builtin.cpu.has(.mips, .mips32r2)) {
            asm volatile ("pause");
        },

        .riscv32,
        .riscv32be,
        .riscv64,
        .riscv64be,
        => if (comptime builtin.cpu.has(.riscv, .zihintpause)) {
            asm volatile ("pause");
        },

        .sparc,
        .sparc64,
        => if (comptime builtin.cpu.hasAny(.sparc, &.{ .v8plus, .v9 })) {
            asm volatile ("rd %%ccr, %%g0");
        },

        else => {},
    }
}

test spinLoopHint {
    for (0..10) |_| {
        spinLoopHint();
    }
}

pub fn cacheLineForCpu(cpu: std.Target.Cpu) u16 {
    return switch (cpu.arch) {
        // x86_64:从 Intel Sandy Bridge 开始,空间预取器每次会成对加载 64 字节缓存行。
        // - https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf
        // - https://github.com/facebook/folly/blob/1b5288e6eea6df074758f877c849b6e73bbb9fbb/folly/lang/Align.h#L107
        //
        // aarch64:部分 big.LITTLE ARM 架构的“大核”使用 128 字节缓存行:
        // - https://www.mono-project.com/news/2016/09/12/arm64-icache/
        // - https://cpufun.substack.com/p/more-m1-fun-hardware-information
        //
        // - https://github.com/torvalds/linux/blob/3a7e02c040b130b5545e4b115aada7bacd80a2b6/arch/arc/Kconfig#L212
        // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_ppc64x.go#L9
        .x86_64,
        .aarch64,
        .aarch64_be,
        .arc,
        .arceb,
        .powerpc64,
        .powerpc64le,
        => 128,

        // https://github.com/llvm/llvm-project/blob/e379094328e49731a606304f7e3559d4f1fa96f9/clang/lib/Basic/Targets/Hexagon.h#L145-L151
        .hexagon,
        => if (cpu.has(.hexagon, .v73)) 64 else 32,

        // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_arm.go#L7
        // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips.go#L7
        // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mipsle.go#L7
        // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips64x.go#L9
        // - https://github.com/torvalds/linux/blob/3a7e02c040b130b5545e4b115aada7bacd80a2b6/arch/sparc/include/asm/cache.h#L14
        // - https://github.com/torvalds/linux/blob/3a7e02c040b130b5545e4b115aada7bacd80a2b6/arch/microblaze/include/asm/cache.h#L15
        // - https://github.com/torvalds/linux/blob/3a7e02c040b130b5545e4b115aada7bacd80a2b6/arch/sh/include/cpu-sh4/cpu/cache.h#L10
        // - https://github.com/openbsd/src/blob/1957873d2063db11dab780eca75b5e629d1e838d/sys/arch/m88k/m88k/atomic.S#L22
        .arm,
        .armeb,
        .thumb,
        .thumbeb,
        .m88k,
        .microblaze,
        .microblazeel,
        .mips,
        .mipsel,
        .mips64,
        .mips64el,
        .sh,
        .sheb,
        .sparc,
        .sparc64,
        => 32,

        // - https://github.com/torvalds/linux/blob/3a7e02c040b130b5545e4b115aada7bacd80a2b6/arch/m68k/include/asm/cache.h#L10
        // - https://github.com/torvalds/linux/blob/3a7e02c040b130b5545e4b115aada7bacd80a2b6/arch/openrisc/include/asm/cache.h#L24
        // - https://github.com/torvalds/linux/blob/3a7e02c040b130b5545e4b115aada7bacd80a2b6/arch/parisc/include/asm/cache.h#L16
        .hppa,
        .hppa64,
        .m68k,
        .or1k,
        => 16,

        // - https://www.ti.com/lit/pdf/slaa498
        .msp430,
        => 8,

        // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_s390x.go#L7
        // - https://sxauroratsubasa.sakura.ne.jp/documents/guide/pdfs/Aurora_ISA_guide.pdf
        .s390x,
        .ve,
        => 256,

        // 其他 x86 和 WASM 平台使用 64 字节缓存行。
        // 假定其余架构也采用类似配置。
        // - https://github.com/golang/go/blob/dda2991c2ea0c5914714469c4defc2562a907230/src/internal/cpu/cpu_x86.go#L9
        // - https://github.com/golang/go/blob/0a9321ad7f8c91e1b0c7184731257df923977eb9/src/internal/cpu/cpu_loong64.go#L11
        // - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_wasm.go#L7
        // - https://github.com/golang/go/blob/19e923182e590ae6568c2c714f20f32512aeb3e3/src/internal/cpu/cpu_riscv64.go#L7
        // - https://github.com/torvalds/linux/blob/3a7e02c040b130b5545e4b115aada7bacd80a2b6/arch/xtensa/variants/csp/include/variant/core.h#L209
        // - https://github.com/torvalds/linux/blob/3a7e02c040b130b5545e4b115aada7bacd80a2b6/arch/csky/Kconfig#L183
        // - https://github.com/torvalds/linux/blob/3a7e02c040b130b5545e4b115aada7bacd80a2b6/arch/alpha/include/asm/cache.h#L11
        // - https://www.xmos.com/download/The-XMOS-XS3-Architecture.pdf
        else => 64,
    };
}

/// CPU 原子更新内存时的估计缓存行大小。
/// 添加此大小的填充,或按此边界对齐,以免原子更新的
/// 内存迫使附近非原子访问的内存缓存失效。
///
/// https://en.wikipedia.org/wiki/False_sharing
/// https://github.com/golang/go/search?q=CacheLinePadSize
pub const cache_line: comptime_int = cacheLineForCpu(builtin.cpu);

test "current CPU has a cache line size" {
    _ = cache_line;
}

/// 无锁且只有一个所有者的资源。
pub const Mutex = enum(u8) {
    unlocked,
    locked,

    pub fn tryLock(m: *Mutex) bool {
        return @cmpxchgStrong(Mutex, m, .unlocked, .locked, .acquire, .monotonic) == null;
    }

    pub fn unlock(m: *Mutex) void {
        assert(@atomicLoad(Mutex, m, .unordered) == .locked);
        @atomicStore(Mutex, m, .unlocked, .release);
    }
};