rust - 替代 std::sync::Semaphore 因为它已被弃用?

标签 rust

文档说它已被弃用。什么是系统信号量?现在这个结构的最佳替代品是什么?

Deprecated since 1.7.0: easily confused with system semaphore and not used enough to pull its weight

最佳答案

系统信号量是指操作系统系统提供的任何信号量。在 POSIX(Linux、MacOS)上,这些是您从 #include <semaphore.h> 获得的方法(man page)。 std::sync::Semaphore是在 Rust 中实现的,并且与操作系统的信号量分开,尽管它确实使用了一些操作系统级别的同步原语(std::sync::Condvar 在 Linux 上是 based 上的 pthread_cond_t )。 std::sync::Semaphore从未稳定下来。 The source code因为信号量包含一个不稳定的属性

#![unstable(feature = "semaphore",
            reason = "the interaction between semaphores and the acquisition/release \
                      of resources is currently unclear",
            issue = "27798")]

header 中的问题号指定 the discussion about this feature .

std 内的最佳替换是 std::sync::CondVar或与 std::sync::Mutex 配对的繁忙循环.选择一个CondVar如果您认为您可能要等待超过几千个时钟周期,则在繁忙的循环中。

Condvar 的文档有好的example如何将它用作(二进制)信号量

use std::sync::{Arc, Mutex, Condvar};
use std::thread;

let pair = Arc::new((Mutex::new(false), Condvar::new()));
let pair2 = Arc::clone(&pair);

// Inside of our lock, spawn a new thread, and then wait for it to start.
thread::spawn(move|| {
    let (lock, cvar) = &*pair2;
    let mut started = lock.lock().unwrap();
    *started = true;
    // We notify the condvar that the value has changed.
    cvar.notify_one();
});

// Wait for the thread to start up.
let (lock, cvar) = &*pair;
let mut started = lock.lock().unwrap();
while !*started {
    started = cvar.wait(started).unwrap();
}

这个例子可以通过改变Mutex::new(false)来适应作为一个计数信号量。至 Mutex::new(0)以及一些相应的更改。

关于rust - 替代 std::sync::Semaphore 因为它已被弃用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59480070/

相关文章:

rust - 如何在 QEMU 模拟器下在 Windows 10 64 位上运行基于 Rust 的 Redox OS 的预编译镜像?

path - 为什么当我将文件推送到 PathBuf 上时,它会丢失当前目录?

rust - 是否可以使用 rustdoc 对 API 的各个部分进行分组?

Rust actix-web : the trait `Handler<_, _>` is not implemented

vector - 如何连接两个切片或两个向量并仍然可以访问原始值?

rust - 如何在 Bevy 中翻转 spritesheet

c++ - Rust与C++ : Returning objects from functions

struct - 我可以限制结构的生命周期污染吗?

rust - 如何在 Rust 中以编程方式使用 Cargo 命令?

rust - 对外部用户弃用,但允许我吗?