queue.queuecollections.deque 命令都给读者提供了一个关于队列的一般概念,但是,两者的应用非常不同,因此不应该被混为一谈。尽管它们是不同的,并且用于非常不同的目的,但就完整的功能而言,它们在某种程度上是相互联系的。在我们进入它们的实际作用以及它们是如何相互联系的之前,有一个概念必须被重新审视,即计算机软件的处理的基本原理。

我们知道,任何程序在活动状态下都会成为一个进程,每个进程都可以被分解为线程,以获得其拥有的优势。我们还知道,两个线程可能需要相互通信,这就是queue.queue的作用。另一方面,Collections.deque被用作一个线程中的数据结构,以执行某些功能。它们之间的联系是,queue.queue在内部使用collections.deque。两者都是处理线程安全的操作。

Queue.Queue: 这个类是用来促进来自同一进程的两个线程之间的通信。不过它的工作方式和典型的队列一样,唯一的区别是它的目的。它拥有multirocessing.queue的所有功能,同时还有两个功能—task_done()和join()。

顾名思义,task_done()是用来通知任务完成的。join()用于要求所有任务等待,直到所有进程都处理完毕。

示例代码:

# import modules
import threading, queue

# setting up a queue for threads
q = queue.Queue()

def execute_thread():
    while True:
        th=q.get()
        print(f'task {th} started')
        print(f'task {th} finished')
        q.task_done()

# set up for threads to work
threading.Thread(target = execute_thread, daemon = True).start()

# sending task requests
for i in range(5):
    q.put(i)
print("all tasks sent")


# making threads wait until all tasks are done
q.join()
print("all tasks completed")

运行结果:

all tasks sent
task 0 started
task 0 finished
task 1 started
task 1 finished
task 2 started
task 2 finished
task 3 started
task 3 finished
task 4 started
task 4 finished
all tasks completed

Collections.Deque: 一个通用的数据结构,它的行为就像一个普通的FIFO队列。在一个线程中使用它来完成一些功能。它的基本实现如下所示:

# import module
from collections import deque

# initialise
dq = deque(['first','second','third'])
print(dq)
deque(['first', 'second', 'third'])

# adding more values
dq.append('fourth')
dq.appendleft('zeroth')
print(dq)
deque(['zeroth', 'first', 'second', 'third', 'fourth'])

# adding value to a specified index
dq.insert(0,'fifth')
print(dq)
deque(['fifth', 'zeroth', 'first', 'second', 'third', 'fourth'])

# removing values
dq.pop()
'fourth'
print(dq)
deque(['fifth', 'zeroth', 'first', 'second', 'third'])
dq.remove('zeroth')
print(dq)
deque(['fifth', 'first', 'second', 'third'])

运行结果:

deque([‘first’, ‘second’, ‘third’])
deque([‘zeroth’, ‘first’, ‘second’, ‘third’, ‘fourth’])
deque([‘fifth’, ‘zeroth’, ‘first’, ‘second’, ‘third’, ‘fourth’])
deque([‘fifth’, ‘zeroth’, ‘first’, ‘second’, ‘third’])
deque([‘fifth’, ‘first’, ‘second’, ‘third’])

| ——- | ——- | ——- |