Python 队列

Posted 短毛兔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 队列相关的知识,希望对你有一定的参考价值。

一、队列

队列是一种先进先出的数据结构,是线程间最常用的交换数据的形式。Queue提供了队列操作模块。

二、队列的基本操作

技术分享图片
import queue

q = queue.Queue(maxsize=10) #可以是指队列长度,默认无限

q.put(1)
q.put(2)
q.put(3)
q.put(4)
q.put(5)
q.put(6)
q.put(7)
q.put(8)
q.put(9)
q.put(10)
# q.put(11) 会阻塞,直到队列中空出一个元素
print(q.full()) #判断队列是否已满 True
print(q.empty()) #判断队列是否为空 False
print(q.get()) #获取队列的元素 1
print(q.get()) #2
队列的基本操作

三、使用队列实现两个子进程之间的通信

from multiprocessing import Process
from multiprocessing import Queue

def producer(q):
    q.put(hello)

def castumer(q):
    print(q.get())


if __name__ == __main__:
    q = Queue()
    p = Process(target=producer,args=(q,))
    p.start()

    c = Process(target=castumer,args=(q,))
    c.start()

四、使用队列实现生产者和消费者

 

以上是关于Python 队列的主要内容,如果未能解决你的问题,请参考以下文章

常用python日期日志获取内容循环的代码片段

python 有用的Python代码片段

Python 向 Postman 请求代码片段

python [代码片段]一些有趣的代码#sort

使用 Python 代码片段编写 LaTeX 文档

python 机器学习有用的代码片段