脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - 关于Python中几种队列Queue用法区别

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

2023-05-02 12:55IT之一小佬 Python

这篇文章主要介绍了关于Python中几种队列Queue用法区别,queue队列中的put()或者get()方法中都提供了timeout参数,利用这个参数可以有效解决上述消除不能消费和线程一直阻塞问题,需要的朋友可以参考下

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

1、from queue import Queue

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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("主程序执行结束!")

注意:上述写法:

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

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

?
1
2
while True:
    x = queue.get()

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

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

示例代码2:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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("主程序执行结束!")

运行结果:

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

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

2、from multiprocessing import Queue

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

示例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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

运行结果:

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

3、from multiprocessing import Manager

示例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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用法区别的文章就介绍到这了,更多相关Python中的队列Queue内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_44799217/article/details/127625019

延伸 · 阅读

精彩推荐
  • PythonPYTHON压平嵌套列表的简单实现

    PYTHON压平嵌套列表的简单实现

    下面小编就为大家带来一篇PYTHON压平嵌套列表的简单实现。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    脚本之家6092020-08-26
  • PythonPython的math模块中的常用数学函数整理

    Python的math模块中的常用数学函数整理

    这篇文章主要介绍了Python的math模块中的常用数学函数整理,同时对运算符的运算优先级作了一个罗列,需要的朋友可以参考下...

    Python教程网9582020-08-11
  • Pythonpython3 requests 各种发送方式详解

    python3 requests 各种发送方式详解

    这篇文章主要介绍了python3 requests 各种发送方式,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...

    hgdzw4492021-10-22
  • Pythonpython实现三次样条插值

    python实现三次样条插值

    这篇文章主要为大家详细介绍了python实现三次样条插值,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    肥宅_Sean16282021-04-30
  • PythonPython装饰器(decorator)定义与用法详解

    Python装饰器(decorator)定义与用法详解

    这篇文章主要介绍了Python装饰器(decorator)定义与用法,结合具体实例形式详细分析了Python装饰器的概念、功能及相关使用技巧,需要的朋友可以参考下...

    初心不忘11932021-01-13
  • Python在Pycharm中安装Pandas库方法(简单易懂)

    在Pycharm中安装Pandas库方法(简单易懂)

    这篇文章主要介绍了在Pycharm中安装Pandas库方法,文中通过图文介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小...

    春末的南方城市6092021-09-06
  • PythonPython 基础教程之包和类的用法

    Python 基础教程之包和类的用法

    这篇文章主要介绍了Python 基础教程之包和类的用法的相关资料,需要的朋友可以参考下...

    阳光柠檬_4622020-09-21
  • Python详解Python爬虫的基本写法

    详解Python爬虫的基本写法

    这篇文章主要介绍了详解Python爬虫的基本写法 的相关资料,需要的朋友可以参考下 ...

    jerrylsxu3022020-08-06