← 中文资源

简体中文版本

fetch_or 原子置位标志位

AtomicU32::fetch_or 置位并返回旧值:并发任务靠它原子认领状态位,先到者胜出,重复置位返回 false,全程无需互斥锁。

阅读英文原文

实现说明

底层就是函数 set_flag、main。

使用要点

  • 每一步打印都带着自己的标签:ready first:、ready again:、all flags:。
  • 运行整个文件:main 会依次驱动 set_flag。

常见问题

运行「fetch_or 原子置位标志位」会打印什么?

运行文件本身,ready first:、ready again:、all flags: 这些前缀各对应一段演示逻辑。

主签名形如 fn set_flag(bit: u32) -> bool

核心语句

fn set_flag(bit: u32) -> bool {
    // fetch_or: sets the bit and returns the value before the call
    let before = FLAGS.fetch_or(bit, Ordering::SeqCst);
    before & bit == 0 // true when this call set the bit first
}

代码示例

use std::sync::atomic::{AtomicU32, Ordering};

const READY: u32 = 1 << 0;
const DONE: u32 = 1 << 1;
const FAILED: u32 = 1 << 2;

static FLAGS: AtomicU32 = AtomicU32::new(0);

fn set_flag(bit: u32) -> bool {
    // fetch_or: sets the bit and returns the value before the call
    let before = FLAGS.fetch_or(bit, Ordering::SeqCst);
    before & bit == 0 // true when this call set the bit first
}

fn main() {
    println!("ready first: {}", set_flag(READY));
    println!("ready again: {}", set_flag(READY));
    set_flag(DONE);
    set_flag(FAILED);
    let all = FLAGS.load(Ordering::SeqCst);
    println!("all flags: {all:#010b}");
    println!("done set: {}", all & DONE != 0);
}