文档说它已被弃用。什么是系统信号量?现在这个结构的最佳替代品是什么?
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/