zoukankan      html  css  js  c++  java
  • Python3标准库:queue线程安全的FIFO实现

    1. queue线程安全的FIFO实现

    queue模块提供了一个适用于多线程编程的先进先出(FIFO,first-in,first-out)数据结构,可以用来在生产者和消费者线程之间安全地传递消息或其他数据。它会为调用者处理锁定,使多个线程可以安全而容易地处理同一个Queue实例。Queue的大小(其中包含的元素个数)可能受限,以限制内存使用或处理。

    1.1 基本FIFO队列

    Queue类实现了一个基本的先进先出容器。使用put()将元素增加到这个序列的一端,使用get()从另一端删除。

    import queue
    
    q = queue.Queue()
    
    for i in range(5):
        q.put(i)
    
    while not q.empty():
        print(q.get(), end=' ')
    print()

    这个例子使用了一个线程来展示按插入元素的相同顺序从队列删除元素。

    1.2 LIFO队列

    与Queue的标准FIFO实现相反,LifoQueue使用了(通常与栈数据结构关联的)后进后出(LIFO,last-in,first-out)顺序。

    import queue
    
    q = queue.LifoQueue()
    
    for i in range(5):
        q.put(i)
    
    while not q.empty():
        print(q.get(), end=' ')
    print()

    get将删除最近使用put插入到队列的元素。

    1.3 优先队列

    有些情况下,需要根据队列中元素的特性来决定这些元素的处理顺序,而不是简单地采用在队列中创建或插入元素的顺序。例如,工资部门的打印作业可能就优先于某个开发人员想要打印的代码清单。PriorityQueue使用队列内容的有序顺序来决定获取哪一个元素。

    import functools
    import queue
    import threading
    
    @functools.total_ordering
    class Job:
    
        def __init__(self, priority, description):
            self.priority = priority
            self.description = description
            print('New job:', description)
            return
    
        def __eq__(self, other):
            try:
                return self.priority == other.priority
            except AttributeError:
                return NotImplemented
    
        def __lt__(self, other):
            try:
                return self.priority < other.priority
            except AttributeError:
                return NotImplemented
    
    q = queue.PriorityQueue()
    
    q.put(Job(3, 'Mid-level job'))
    q.put(Job(10, 'Low-level job'))
    q.put(Job(1, 'Important job'))
    
    def process_job(q):
        while True:
            next_job = q.get()
            print('Processing job:', next_job.description)
            q.task_done()
    
    workers = [
        threading.Thread(target=process_job, args=(q,)),
        threading.Thread(target=process_job, args=(q,)),
    ]
    for w in workers:
        w.setDaemon(True)
        w.start()
    
    q.join()

    这个例子有多个线程在处理作业,要根据调用get()时队列中元素的优先级来处理。运行消费者线程时,增加到队列的元素的处理顺序取决于线程上下文切换。

  • 相关阅读:
    file is universal (3 slices) but does not contain a(n) armv7s slice error for static libraries on iOS
    WebImageButton does not change images after being enabled in Javascript
    ajax OPTION
    编程遍历页面上所有TextBox控件并给它赋值为string.Empty?
    获取海洋天气预报
    C#线程系列教程(1):BeginInvoke和EndInvoke方法
    js控制只能输入数字和小数点
    Response.AddHeader(,)
    ManualResetEvent的理解
    Convert.ToInt32、int.Parse(Int32.Parse)、int.TryParse、(int) 区别
  • 原文地址:https://www.cnblogs.com/liuhui0308/p/12343274.html
Copyright © 2011-2022 走看看