关于Python中几种队列Queue用法区别

 更新时间:2023年05月01日 09:00:25   作者:IT之一小佬  
这篇文章主要介绍了关于Python中几种队列Queue用法区别,queue队列中的put()或者get()方法中都提供了timeout参数,利用这个参数可以有效解决上述消除不能消费和线程一直阻塞问题,需要的朋友可以参考下

python中使用到的队列模块大致有三个:

1、from queue import Queue

此模块适用于线程间通信,但不能用于进程间通信。

示例代码1: 【注意:此时代码存在错误!!!】

import time
import threading
from queue import Queue
def task_func():
    global queue
    while queue.qsize() > 0:
        x = queue.get()
        print(f"num: {x}")
        time.sleep(0.1)
def producer_data():
    global queue
    for i in range(100):
        queue.put(i)
        time.sleep(0.1)
if __name__ == '__main__':
    queue = Queue()
    producer_thread = threading.Thread(target=producer_data)
    producer_thread.start()
    thread_list = []
    for i in range(5):
        thread = threading.Thread(target=task_func)
        thread.start()
        thread_list.append(thread)
    for thread in thread_list:
        thread.join()
    print("主程序执行结束!")

注意:上述写法:

    while queue.qsize() > 0:
        x = queue.get()

当生产者速度没有消费者速度快时,上述消费者代码会提前结束,导致生产者的速度不能消费。

    while True:
        x = queue.get()

这种写法也存在问题,此时消费者队列会一直监听生产者队列是否有数据,导致线程一直处于阻塞状态,程序会一直阻塞不会停止,严重浪费系统资源。如果使用apscheduler等定时任务的库的话,会导致定时任务无法启动。

其实queue队列中的put()或者get()方法中都提供了timeout参数,利用这个参数可以有效解决上述消除不能消费和线程一直阻塞问题。

示例代码2:

import time
import threading
from queue import Queue
def task_func():
    global queue
    while True:
        x = queue.get(timeout=10)
        print(f"num: {x}")
def producer_data():
    global queue
    for i in range(100):
        queue.put(i)
        time.sleep(0.1)
if __name__ == '__main__':
    queue = Queue()
    producer_thread = threading.Thread(target=producer_data)
    producer_thread.start()
    thread_list = []
    for i in range(5):
        thread = threading.Thread(target=task_func)
        thread.start()
        thread_list.append(thread)
    for thread in thread_list:
        thread.join()
    print("主程序执行结束!")

运行结果:

根据不同的情境,可以根据实际情况设置timeout的值。如果使用定时任务,使用timeout是可以的,不会使程序抛异常停止的。

2、from multiprocessing import Queue

此模块用于对进程,但是不能用于进程池

示例代码:

import time
from multiprocessing import Process, Queue
import queue
def producer(queue):
    queue.put("a")
    time.sleep(2)
def consumer(queue):
    time.sleep(2)
    data = queue.get()
    print(data)
if __name__ == "__main__":
    # queue = queue.Queue()
    queue = Queue()
    my_producer = Process(target=producer, args=(queue, ))
    my_consumer = Process(target=consumer, args=(queue, ))
    my_producer.start()
    my_consumer.start()
    my_producer.join()
    my_consumer.join()
# 使用queue模块的Queue()会报错
# 使用multiprocessing中的Queue(),正确输出a
 

运行结果:

3、from multiprocessing import Manager

示例代码:

import time
from multiprocessing import Process, Queue, Pool, Manager
def producer(queue):
    queue.put("a")
    time.sleep(2)
def consumer(queue):
    time.sleep(2)
    data = queue.get()
    print(data)
if __name__ == "__main__":
    # queue = Queue()
    queue = Manager().Queue()
    pool = Pool()
    # pool中的进程间通信需要使用Manager
    pool.apply_async(producer, args=(queue, ))
    pool.apply_async(consumer, args=(queue, ))
    pool.close()
    pool.join()

运行结果:

到此这篇关于关于Python中几种队列Queue用法区别的文章就介绍到这了,更多相关Python中的队列Queue内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • flask框架中的cookie和session使用

    flask框架中的cookie和session使用

    这篇文章主要介绍了flask框架中的cookie和session使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • Python学习之异常处理的避坑指南

    Python学习之异常处理的避坑指南

    这篇文章主要介绍了Python中异常处理的一些避坑指南,文中的示例代码讲解详细,对我们学习Python有一定帮助,感兴趣的小伙伴可以学习一下
    2022-03-03
  • scipy.interpolate插值方法实例讲解

    scipy.interpolate插值方法实例讲解

    这篇文章主要介绍了scipy.interpolate插值方法介绍,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-12-12
  • Python视频编辑库MoviePy的使用

    Python视频编辑库MoviePy的使用

    这篇文章主要介绍了Python视频编辑库MoviePy的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • 小米5s微信跳一跳小程序python源码

    小米5s微信跳一跳小程序python源码

    这篇文章主要为大家详细介绍了小米5s微信跳一跳小程序python源码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01
  • Python 脚本获取ES 存储容量的实例

    Python 脚本获取ES 存储容量的实例

    今天小编就为大家分享一篇Python 脚本获取ES 存储容量的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-12-12
  • Biblibili视频投稿接口分析并以Python实现自动投稿功能

    Biblibili视频投稿接口分析并以Python实现自动投稿功能

    这篇文章主要介绍了Biblibili视频投稿接口分析并以Python实现自动投稿功能,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-02-02
  • Python使用Docling库玩转文档处理

    Python使用Docling库玩转文档处理

    Docling 是一个强大的 Python 第三方库,专注于文档处理和转换,所以本文将带大家深入了解 Docling 的强大功能,展示它如何帮助我们高效处理文档,感兴趣的可以了解下
    2025-02-02
  • OpenCV Python实现拼图小游戏

    OpenCV Python实现拼图小游戏

    这篇文章主要为大家详细介绍了OpenCV Python实现拼图版小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-03-03
  • python pyg2plot的原理知识点总结

    python pyg2plot的原理知识点总结

    在本篇文章里小编给大家整理的是一篇关于python pyg2plot的原理知识点总结内容,有兴趣的朋友们可以参考下。
    2021-02-02

最新评论