这是天真的阻止队列吗?

问题描述

以下是阻塞队列的正确实现吗?

更正为:

  1. 线程安全,即在多线程方案中具有队列的语义。
  2. 如果为空,则在尝试检索元素时阻塞。
  3. 如果已满(在这种情况下为std::u8::MAX,则在尝试添加新元素时会阻塞。

根据我的静态分析,我认为它可以避免死锁;但是我知道同步有多棘手。

此实现是否存在明显的错误,会阻止我在生产中使用? (假设的情况)
如果此实现是正确的,那么与适当的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())
        }
    }
}

注意:

  1. 信号量是我自己创造的。让我们假设它已正确实施。
  2. bounded_queue尝试防止插入超出std::u8::MAX的地方。
  3. non_empty_queue尝试阻止空时的“爆裂声”。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)