【发布时间】:2021-11-02 19:01:37
【问题描述】:
我需要一个可以被多个线程访问的全局布尔标志。
这是我需要的示例:
static GLOBAL_FLAG: SyncLazy<Mutex<bool>> = SyncLazy::new(|| {
Mutex::new(false)
});
fn set_flag_to_true() { // can be called by 2+ threads concurrently
*GLOBAL_FLAG.lock().unwrap() = true;
}
fn get_flag_and_set_to_true() -> bool { // only one thread is calling this function
let v = *GLOBAL_FLAG.lock().unwrap(); // Obtain current flag value
*GLOBAL_FLAG.lock().unwrap() = true; // Always set the flag to true
v // Return the previous value
}
get_flag_and_set_to_true() 的实现感觉不太对劲。我想最好只锁一次。最好的方法是什么?
顺便说一句,我想Arc<[AtomicBool]> 也可以使用,理论上应该更快,尽管在我的特定情况下,速度优势并不明显。
【问题讨论】:
-
只是将
GLOBAL_FLAG.lock().unwrap()存储在变量中?当它在函数结束时消失时,锁将被释放
标签: rust concurrency mutex