Spiga

用Go撸数据结构(五):队列

2020-06-14 13:52:14

一、什么是队列?

1.先进者先出,这就是典型的“队列”结构。
2.支持两个操作:入队enqueue(),放一个数据到队尾;出队dequeue(),从队头取一个元素。
3.所以,和栈一样,队列也是一种操作受限的线性表。

二、如何实现队列

1. 数组实现

type Queue struct {
    items []interface{}
    length int //数组大小
    head int //表示队头下标
    tail int //表示队尾下标
 }
 func CreateStack(cap int) *Queue {
    if cap == 0 {
	panic("不能创建容量为0的队列!")
    }
    return &Queue{
        items: [capacity]interface,
        length: capacity,
        head:0,
        tail:0
    }
}
 
 func (this *Queue) Enqueue(item interface{})(err error){
    if this.tail == this.length {
       return errors.New("queue full")
    }
    this.items[this.rear] = item
    this.tail++
    return
 }
 func (this *Queue) Dequeue() (interface{},err error){
    if this.head == this.tail {
       return _,errors.New("queue empty")
    }
    item = this.items[this.head]
    this.head++
    return item,err
 }

比起栈的数组实现,队列的数组实现稍微有点儿复杂。

对于栈来说,我们只需要一个栈顶指针就可以了。但是队列需要两个指针:一个是 head 指针,指向队头;一个是 tail 指针,指向队尾。

如下图:当 a、b、c、d 依次入队之后,队列中的 head 指针指向下标为 0 的位置,tail 指针指向下标为 4 的位置。

当我们调用两次出队操作之后,队列中 head 指针指向下标为 2 的位置,tail 指针仍然指向下标为 4 的位置。

你肯定已经发现了,随着不停地进行入队、出队操作,head 和 tail 都会持续往后移动。当 tail 移动到最右边,即使数组中还有空闲空间,也无法继续往队列中添加数据了。这个问题该如何解决呢?

实际上,我们在出队时可以不用搬移数据。如果没有空闲空间了,我们只需要在入队时,再集中触发一次数据的搬移操作。借助这个思想,出队函数 dequeue() 保持不变,我们稍加改造一下入队函数 enqueue() 的实现,就可以轻松解决刚才的问题了。下面是具体的代码:

func (this *Queue) Enqueue() (*item interface{},err error){ 
     // tail == length表示队列末尾没有空间了 
     if this.tail == this.length { 
        // tail ==length && head==0,表示整个队列都占满了 
        if this.head == 0 {
            return errors.New("queue full")
        }
        // 数据搬移 
        for i := head; i < tail; i++ { 
            this.items[i-head] = this.items[i]
        } 
        // 搬移完之后重新更新head和tail 
        this.tail -= this.head
        this.head = 0
    } 
    this.items[tail] = item
    this.tail++
}

从代码中我们看到,当队列的 tail 指针移动到数组的最右边后,如果有新的数据入队,我们可以将 head 到 tail 之间的数据,整体搬移到数组中 0 到 tail-head 的位置。

2. 链表实现

type (
    //Queue 队列
    Queue struct {
        head    *node
        tail   *node
        length int
    }
    //双向链表节点
    node struct {
        pre   *node
        next  *node
        value interface{}
    }
)

func New() *Queue {
    return &Queue{nil, nil, 0}
}
//入队操作
func (this *Queue) Push(v interface{}) {
    n := &node{nil, nil, v}
    if this.length == 0 {
        this.head = n
        this.tail = this.head
    } else {
        n.pre = this.tail
        this.tail.next = n
        this.tail = n
    }
    this.length++
}
//出队操作
func (this *Queue) Pop() interface{} {
    if this.length == 0 {
        return nil
    }
    n := this.head
    if this.head.next == nil {
        this.head = nil
    } else {
        this.head = this.top.next
        this.head.pre.next = nil
        this.head.pre = nil
    }
    this.length--
    return n.value
}

三、队列有哪些常见的应用?

1. 阻塞队列

  • 在队列的基础上增加阻塞操作,就成了阻塞队列。
  • 阻塞队列就是在队列为空的时候,从队头取数据会被阻塞,因为此时还没有数据可取,直到队列中有了数据才能返回;如果队列已经满了,那么插入数据的操作就会被阻塞,直到队列中有空闲位置后再插入数据,然后在返回。
  • 从上面的定义可以看出这就是一个“生产者-消费者模型”。这种基于阻塞队列实现的“生产者-消费者模型”可以有效地协调生产和消费的速度。当“生产者”生产数据的速度过快,“消费者”来不及消费时,存储数据的队列很快就会满了,这时生产者就阻塞等待,直到“消费者”消费了数据,“生产者”才会被唤醒继续生产。不仅如此,基于阻塞队列,我们还可以通过协调“生产者”和“消费者”的个数,来提高数据处理效率,比如配置几个消费者,来应对一个生产者。

2. 并发队列

  • 在多线程的情况下,会有多个线程同时操作队列,这时就会存在线程安全问题。能够有效解决线程安全问题的队列就称为并发队列。
  • 并发队列简单的实现就是在enqueue()、dequeue()方法上加锁,但是锁粒度大并发度会比较低,同一时刻仅允许一个存或取操作。
  • 实际上,基于数组的循环队列利用CAS原子操作,可以实现非常高效的并发队列。这也是循环队列比链式队列应用更加广泛的原因。

3. 线程池资源枯竭是的处理

  • 对于大部分资源有限的场景,当没有空闲资源时,基本上都可以通过“队列”这种数据结构来实现请求排队。