问题描述
以下是阻塞队列的正确实现吗?
更正为:
根据我的静态分析,我认为它可以避免死锁;但是我知道同步有多棘手。
此实现是否存在明显的错误,会阻止我在生产中使用? (假设的情况)
如果此实现是正确的,那么与适当的BlockingQueue
相比,性能上的缺点是什么?为什么?
use std::collections::VecDeque;
use crate::Semaphore;
use std::sync::Mutex;
pub struct BlockingQueue<T> {
non_empty_queue: Semaphore,bounded_queue: Semaphore,data: Mutex<VecDeque<T>>
}
impl<T> BlockingQueue<T> {
pub fn poll(&self) -> T {
self.non_empty_queue.decrement();
let mut lock_guard = self.data.lock().expect("Unable to acquire lock ...");
let result = lock_guard.pop_back().expect("Major flaw!");
self.bounded_queue.increment();
result
}
pub fn offer(&self,t: T) -> () {
self.bounded_queue.decrement();
let mut lock_guard = self.data.lock().expect("Unable to acquire lock ...");
lock_guard.push_front(t);
self.non_empty_queue.increment();
}
pub fn new() -> BlockingQueue<T> {
BlockingQueue {
non_empty_queue: Semaphore::new(0),bounded_queue: Semaphore::new(std::u8::MAX),data: Mutex::new(VecDeque::new())
}
}
}
注意:
- 信号量是我自己创造的。让我们假设它已正确实施。
-
bounded_queue
尝试防止插入超出std::u8::MAX
的地方。 -
non_empty_queue
尝试阻止空时的“爆裂声”。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)