queue Thread-Safe FIFO Implementation

简介: queue Thread-Safe FIFO Implementation

queue: Thread-Safe FIFO Implementation

This queue module provides a (FIFO) data structure suitable for multi-threaded programming. It can be used to pass messages or other data between producer and consumer threads safely. Locking is handled for the caller , so many threads can work with the same Queue instance safely and easily. The size of a Queue

1.1 Basic FIFO Queue

The Queue class implements a basic , container. Elements are added to one “end” of the sequence using put() , and removed from the other end using get().

The following is programming codes:

import queue

q = queue.Queue()

for i in range(5):
    q.put(i)


while not q.empty():
    print(q.get(), end=' ')
print()

This example uses a single thread to illustrate that elements are removed from the queue in the same order in which they are inserted.

the result :

D:\Python39\python.exe D:/My_Project/queque_demo1.py
0 1 2 3 4 

Process finished with exit code 0

1.2 LIFO Queue
In contrast to the standard FIFO implementation of Queue, the LifeQueue

The following is programming codes:

import queue

q = queue.LifoQueue()

for i in range(5):
    q.put(i)


while not q.empty():
    print(q.get(), end=' ')
print()

The item most recently put into the queue is removed by get.

the result:

D:\Python39\python.exe D:/My_Project/queque_demo1.py
4 3 2 1 0 

Process finished with exit code 0

1.3 Priority Queue

Sometimes the processing order of the items in a queue needs to be based on characteristics of those items, rather than just the order they are created or added to the queue. For example, print jobs from the payroll department may take precedence over a code listing that a developer wants to print. PriorityQueue

The following is programming codes:

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 1:
        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.daemon = True
    w.start()
q.join()

This example has multiple threads consuming the jobs, which are processed based on the priority of items in the queue at the time get()

The result:

D:\Python39\python.exe D:/My_Project/queque_demo1.py
New job: Mid-level job
New job: low-level job
New job: Important job
Processing job: Important job
Processing job: Mid-level job
Processing job: low-level job

Process finished with exit code 0
相关文章
|
Python
双端优先级队列(Double-Ended Priority Queue
双端优先级队列(Double-Ended Priority Queue)是一种支持在两端进行插入和删除操作的优先级队列。它可以在 O(log n) 的时间复杂度内完成插入、删除、查询操作。双端优先级队列可以使用二叉堆或线段树等数据结构实现。
269 6
|
6月前
|
存储 前端开发 算法
C++线程 并发编程:std::thread、std::sync与std::packaged_task深度解析(一)
C++线程 并发编程:std::thread、std::sync与std::packaged_task深度解析
215 0
已解决 RuntimeError: There is no current event loop in thread ‘Thread-1‘.
Jetson Xavier NX 报错 RuntimeError: There is no current event loop in thread 'Thread-1'.异常错误,已解决
506 0
已解决 RuntimeError: There is no current event loop in thread ‘Thread-1‘.
|
6月前
|
存储 并行计算 Java
C++线程 并发编程:std::thread、std::sync与std::packaged_task深度解析(二)
C++线程 并发编程:std::thread、std::sync与std::packaged_task深度解析
248 0
|
5月前
|
设计模式 算法 C++
satck和queue以及priority_queue
satck和queue以及priority_queue
35 1
中断-softirq-tasklet-work queue(下)
中断-softirq-tasklet-work queue
75 0
|
存储 算法 C++
C++ priority_queue
C++ priority_queue
|
存储 算法 程序员
stack、queue、priority_queue的使用和简单实现【STL】
stack、queue、priority_queue的使用和简单实现【STL】
60 0
|
Linux 调度
中断-softirq-tasklet-work queue(上)
中断-softirq-tasklet-work queue
92 0
C++ --priority_queue实现
1. 普通版本实现优先级队列 1.1 push()
63 0